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

Photon Weather Shield Hookup Guide

$
0
0

Photon Weather Shield Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

Have you ever wanted to have your own weather station? Or how about your own thermostat capable of controlling your home climate from the Web? Using the Photon module from Particle coupled with the Photon Weather shield from SparkFun, you can now connect your weather related project to the Internet of Things!

SparkFun_Weather_Shield_for_the_Photon

Please Note: All SparkFun shields for the Photon are also compatible with the Core from Particle. The WKP, DAC and VBT pins on the Photon will be labeled A7, A6 and 3V3*, respectively, on the Core, but will not alter the functionality of any of the Shields.

Covered in this Tutorial

This tutorial will cover all the hardware features on the board, all the libraries and firmware you need to communicate with the sensors, how to communicate with said sensors, and how to add additional sensors and parts to create a fully-functional, Internet-connected weather station.

Suggested Materials

I you are looking to just measure Temperature, Humidity, and/or Barometric Pressure (Altitude), you can integrate the Photon Weather Shield into your project right out of the box! No soldering necessary!

The Weather Shield also has numerous optional ports on which other sensors or other devices, such as Bluetooth or XBees, can be added. If you wish to follow along with the weather station project at the end of this tutorial, you can find the parts used in the wish list below.

We really wanted to create a customizable shield for numerous weather project applications. You can add or omit any of the sensors you see throughout this tutorial as well as adding parts not mentioned here.

Suggested Reading

The following are suggestions for other resources to read before getting started with your Photon Weather Shield.

If you have never worked with the Photon or the Core before, we highly recommend visiting the getting started documentation available on the Particle site.

If you are interested in collecting and storing weather data, our Getting started with Phant tutorial is a great place to start.

The Photon Weather Shield borrowed heavily from the Arduino Weather Shield design while also taking customer feedback into consideration to create a more versatile product. There’s lots to be learned from the Hookup Guide for that shield as well.

Our WIMP Weather Station tutorial has lots of great information on how to create a truly weather-proof weather station that can withstand the elements (including wind!). This is a must read if you intend to house your project outdoors.

Check out the Hookup Guides for each of the sensors located on the shield for more information specific to that sensor.

If you are unfamiliar with any of the concepts below, we suggest checking out those tutorials as well.

Hardware Overview & Assembly

The Photon Weather Shield has a lot of functionality packed into one tiny package. Let’s go over each section of the shield.

Photon Footprint

Both the Core and the Photon fit right onto the shield. Copper pours underneath the antenna were restricted so as not to interfere with wireless connections. Each pin is also broken out to the sides of the Photon for accessibility. When attaching a Photn, be sure to line up the beveled end of the Photon with the beveled silkscreen on the PCB.

Photon Footprint

Power

The simplest way to power the shield is to attach a Photon, and then power the Photon through the micro USB connector. This will power the Photon as well as all the components on the shield.

normal power scheme

The downside to that power scheme is that micro USB connectors tend to be fragile when put under a lot of mechanical stress, and they can rip right off the PCB if pulled too hard. Thus, we provided a few other options for power connectors. On the underside of the shield, you’ll find a footprint for both an SMD Barrel Jack and a 2-pin, 3.5mm screw terminal. Either of these can be soldered to the PCB and used for alternate power inputs. The maximum voltage supplied on these alternate connectors should not exceed 12V. For a detailed explanation, read on.

alt text

Powered through the Barrel Jack.

For the screw terminal, you can solder it to either side of the shield, since it fits underneath the Photon. Be sure to keep track of which pin is (+) and which is (-).

alt text

Powered through the Screw Terminal.

On-Board 3.3V Regulator & Power Solder Jumpers

There is also a 3.3V regulator on the shield. If you are powering the Photon through the micro USB connector, this regulator is bypassed. Powering through one of the alternative power connectors mentioned above routes power through the shield’s 3.3V regulator, which is then tied to the 3.3V rail on the Photon, powering it as well.

3.3V Regulator

On-board 3.3V regulator and accompanying circuitry.

The main benefit to using the on-board regulator is that is has a higher maximum voltage rating than the regulator located on the Photon. As stated in the Photon datasheet, if power is supplied directly to the VIN pin on the Photon , the voltage should be regulated between 3.6VDC and 5.5VDC. In contrast, the MIC5219 regulator is rated for 2.5VDC to 12VDC, as per its datasheet.

However, if you would rather have the alternative power source route power through the regulator on the Photon (for lower current consumption during sleep perhaps), simply cut the trace on the Power Select jumper (between the VREG and RAW pads), and add a blob of solder between Raw and P_VIN (Photon VIN) pads. Just be sure to not exceed voltages of 5.5-6V once this alteration has been made.

power solder jumpers

Warning! Never power the Photon/Shield through both the micro USB connector and the barrel jack or screw terminal at the same time! If you need both connected for whatever reason (programming in DFU mode over USB while powered via the barrel jack, for example), you’ll need to cut the trace on the 3.3V Disable jumper, pictured below. Only cut this trace is you have not altered the Power Select jumper

3.3V Disable jumper

On-Board Sensors

The weather shield comes with two on-board sensors. Together, these two sensors can give you a lot of information about the environmental conditions around you or your project.

HTU21D Humidity & Temperature Sensor

The HTU21D is a low-cost, highly accurate, digital humidity and temperature sensor. This sensor communicates over I2C and comes connected to the Photon’s I2C bus by default, making development a breeze. The PCB around this sensor is milled out and copper pour is restricted in that area to reduce the amount of parasitic heat coming from other components on the shield, including the Photon itself, that may affect your temperature readings.

HTU21D

MPL3115A2 Barometric Pressure

The MPL3115A2 is a MEMS pressure sensor that provides Altitude data to within 30cm. The sensor outputs are digitized by a high resolution 24-bit ADC and transmitted over I2C. Pressure output can be resolved with output in fractions of a Pascal, and Altitude can be resolved in fractions of a meter. The device also provides 12-bit temperature measurements in degrees Celsius. This sensor also communicates over I2C and comes connected to the Photon’s I2C bus by default.

MPL3115A2

More information on how to use these sensors can be found in the Libraries and IDE section of this tutorial.

RJ-11 Weather Meter Connectors

If you would like to place your Weather Shield outdoors and create a fully-functional weather station, you can grab a set of Weather Meters and connect them to the RJ-11 connectors located on the Weather Shield. With these meters attached, you can measure wind speed, wind direction and rainfall.

meter connectors

Soil Moisture & Soil/Water Temperature

For those who want to keep track of their houseplant conditions or for those who want to know topsoil conditions in their gardens, the weather shield has an optional port for a soil moisture sensor (Coming Soon!) Leaving the soil moisture sensor powered all the time leads to corrosion of the probes. To account for this, this port breaks out Digital Pin D5 as the power pin for the sensor, allowing the Photon to power the sensor, take a reading, and then disable power, giving the probes a longer lifespan. The moisture level can be read on Analog Pin A1.

Soil Mositure Port

In addition to soil moisture, you can also add a waterproof temperature senor. Whether you have a pond you’d like to monitor near your weather station or you want to know if the ground is still frozen or not, this can be a great addition to any weather station. The waterproof version of the DS18B20 temperature senor is a go-to option for many users looking to sense the temperature of various environments that may not be so kind to electronics. A port for this senors is broken out along with the necessary 4.7K pull-up resistor located between the Vcc and Signal lines. The Signal line is connected to Digital Pin D4. Communicate with this sensor using the OneWire and Dallas Temperature libraries.

Soil Temp

Assembly

The waterproof temp sensor comes with plenty of cable length and pre-stripped, pre-soldered wires on the end, making assembly straightforward. For the Soil Moisture sensor, you’ll have to get a little more creative. You could always just use some hookup wire. We’ve found that retired cables, such as USB cables, can be sacrificed to make cables for such projects. A black USB cable with the green wire snipped matches the look of the DS18B20 cable quite well.

alt text

The snipped USB cable (right) and the DS18B20 cable (left), both secured to standoffs with zip ties.

I2C Port

I2C is becoming increasingly popular as a means by which to communicate with sensors. Thus, it made sense to add an I2C port to allow users to add other sensors to their project. One great example would be adding an external light sensor. Since most weather stations need to be enclosed in a weather proof housing, having a light sensor on-board didn’t make much sense. However, adding the I2C port allows one to connect sensors such as the TSL2561 Luminosity Sensor or the ISL29125 RGB Light Sensor along with a whole slew of other I2C sensors.

I2C Port

I2C Pull-ups

Many SparkFun I2C Breakouts have solder jumpers for disabling the pull-up resistors necessary on most I2C designs. The Photon Weather Shield is no different. If you already have a sensor that has pull-ups, you can disable them on the shield by cutting the traces with a hobby knife. Or, if you would rather leave the shield as is, you can disable the pull-ups on every I2C you add to the bus. The important thing to remember is that only one device on the bus needs to have its pull-ups active. All others should be disabled.

I2C Pullups

Serial 1 Port

Last but not least, there is another port broken out, this time for the USART Serial 1 port on the Photon. Serial ports are great for debugging. They also allow for various other wireless technologies to be attached for mesh networking or for user feedback via an LCD or other display. Let’s say you wanted additional sensors around you home, well beyond the range of your WiFi signal. You could attach an Xbee Explorer to the Serial 1 port on the Weather shield and have your other node (consisting of a stand-alone XBee or an XBee Arduino combo, for example) out in the field, feeding data back to the Photon, which then sends the collective data to the web.

Serial Port

Another use case is wanting to have your weather station outside while still receiving data on a display indoors somewhere. This could easily be accomplished by attaching a BlueSMiRF Bluetooth module to the Serial 1 port and having another BlueSMiRF attached to a Serial Graphic LCD display installed in your home. We’ll show you how to do exactly that later in this tutorial, amongst many other examples.

alt text

A SparkFun BlueSMiRF Silver connected to the Serial 1 Port using a 6-pin, right angle female header with the outermost pins removed.

The pins on the shield match up with any of our BlueSMiRF modules. For other wireless solutions, you may have to wire each pin manually as they may not match up exactly.

Particle Libraries and the Partilce IDE

The Particle team has created both an online and a desktop version of their programming IDE. The online version is referred to as Particle Build. The desktop version is referred to as Particle Dev. It can be downloaded here. Documentation on how to use Particle Dev can be found here. The libraries and example sketches presented throughout this tutorial will work in both versions, however, the means by which each is accomplished will vary slightly.

When dealing with many libraries, you may find it easier to use the Particle Dev desktop IDE as it is easier to add entire project folders. However, if you prefer to use the online IDE or are using a Linux computer, which does not have a desktop version of the IDE at this time, you can still follow along.

Once you have the IDE of your choice setup, visit GitHub, and download the SparkFun Photon Weather Shield Repository. You can also download the .zip file by clicking the link below.

SparkFun Photon Weather Shield Repository

Once the download is complete, open the folder, and navigate to the Firmware folder. Each example uses a variety of different libraries. There are too many to go over in detail here. However, they are all linked below if you would like to learn more about a given library.

Each project folder contains the corresponding library files needed to compile that sketch. It’s redundant as far as storage is concerned, but it makes importing each project folder much easier.

Adding Projects to Particle Dev

To add a project folder to Particle Dev, simply click File -> Add Project Folder, and select the project of your choice.

adding a project to particle dev

Adding Projects to Particle Build

Unfortunately, there is no way to import project folders into the online IDE at this time, so each library will need to be added individually. Adding a library in Particle Build requires you to search for that library in their library manager. Once found, you can click the Include In App button to add that library to your project.

add library in particle build

Each example will state which libraries are needed for it to work.


Now that you know how to work within the Particle IDE, lets upload some code!

Example 1: Getting Started & Reading the On-Board Sensors

For this first example, we’re going to keep it simple. This code will get data from the two on-board sensors and print that information to the Serial port. Your Photon will need to be plugged into a USB port on your computer in order to read the input in a Serial Terminal. You’ll need a Micro USB cable, which you should have if you bought Photon kit.

This first example will detail how to use each version of the Particle IDE. Each example after this will assume you know how to navigate each.

Particle Dev

Open Particle Dev. Click File -> Add Project Folder. Navigate to where you downloaded the SparkFun Photon Weather Shield repo, and select the ‘SparkFun_Photon_Weather_Basic’ folder. Click open, and the folder will be added to the left hand sidebar. You can also drang and drop folders into the IDE. The .ino file along with the library files will be avaialble here. Double-click the SparkFun_Photon_Weather_Basic.ino file to see the sketch.

Explore the sketch. Read the comments. Make any changes you want. Once you’re ready to upload, you’ll need to first select your target device. Click the crosshair looking symbol on the left hand menu to select your device.

select target

Note: You may be required to sign in to your Particle Cloud account (created for free at Particle.io), if you have not do so before. While this IDE is available offline, programming still happens over a WiFi connection. Thus, an Internet connection is still necessary to use Particle Dev.

You’ll be presented with a list of all your Particle devices. Select the correct target. Click the circle with a check mark to compile your code and check for any errors.

alt text

If everything compiles without error, click the lightning bolt symbol to upload you code.

alt text

Heads up! Particle Dev does not check to see if any changes were made before you upload. Thus, any changes made to a sketch must be saved manually before the will take affect and get uploaded. Changes made without saving will not be uploaded.

Particle Build

Create a new App by typing a name in the ‘Current App’ field and pressing ‘Enter’.

alt text

When using Particle Build, you’ll need to add each library individually. Search for ‘sparkfun_mpl’ in the “Libraries” tab to find the SparkFun MPL3115A2 Particle Library. Once found, click on the library.

alt text

Select INCLUDE IN APP, and add it to your desired code file.

Include library in app

Any sketch using the external libraries needs to have the library “included” first.

Repeat the same process for the HTU21D Particle Library.

alt text

What You Should See

Once everything has uploaded correctly, open your favorite Serial Terminal program at 9600-8-N-1-NONE. Select the serial port your Photon has showed up as, and click connect. You should see something like the following print out in the window.

basic serial print

Example 2: Adding External Senors

This example will show you how to control any and all external senors attached to the Weather Shield including the Soil Moisture Sensor, Waterproof Temperature Sensor, and the Weather Meters.

To start, we’ll just add control of both the Soil sensors to our code, then we’ll add the Weather Meter code.

Soil Senors Example

Particle Dev

Open Particle Dev. Click File -> Add Project Folder. Navigate to where you downloaded the SparkFun Photon Weather Shield repo, and select the ‘SparkFun_Photon_Weather_Basic_Soil’ folder. Click open, and the folder will be added to the left hand sidebar. The .ino file along with the library files will be avaialble here. Double-click the SparkFun_Photon_Weather_Basic_Soil.ino file to see the sketch.

Select your target device, compile and upload the sketch.

Particle Build

Create a new App by typing a name in the ‘Current App’ field and pressing ‘Enter’.

alt text

Search for ‘onewire’ in the “Libraries” tab to find the OneWire Particle Library. Once found, click on the library.

alt text

Select INCLUDE IN APP, and add it to your desired code file.

alt text

Any sketch using the external libraries needs to have the library “included” first.

Repeat the same process for the Dallas Temperature Particle Library, as well as the SparkFun_MPL3115A2 library and HTU21D Library used in the previous example. You should have four libraries total for this example.

alt text

What You Should See

Once everything has uploaded correctly, open your favorite Serial Terminal program at 9600-8-N-1-NONE. Select the serial port your Photon has showed up as, and click connect. You should see something like the following print out in the window:

alt text

Click for a larger view.

Weather Meters

Building off the last two examples, we can complete the package by adding the weather meter code. The meters do not require any external libraries. However, if you are using the on-board sensors as well as the soil sensors, which is assumed in the example sketch, then you will need the four previous libraries we have used so far: OneWire, DallasTemperature, HTU21D, and the SparkFun_MPL3115A2 libraries.

Particle Dev

Open Particle Dev. Click File -> Add Project Folder. Navigate to where you downloaded the SparkFun Photon Weather Shield repo, and select the ‘SparkFun_Photon_Weather_Basic_Soil_Meters’ folder. Click open, and the folder will be added to the left hand sidebar. The .ino file along with the library files will be avaialble here. Double-click the SparkFun_Photon_Weather_Basic_Soil_Meters.ino file to see the sketch.

Select your target device, compile and upload the sketch.

Particle Build

The easiest way to go about this would be to use the app you made for the soil sensors and copy and paste this example of the previous sketch. Otherwise you’ll have to create a new app and add all the libraries again.

What You Should See

Once again, open your favorite Serial Terminal program at 9600-8-N-1-NONE. Select the serial port your Photon has showed up as, and click connect. You should see something like the following print out in the window:

alt text

Click for a larger view.

Example 3: Collecting Weather Data Online

Printing to the Serial Terminal is fun and all, but let’s get this thing on the Internet! One of the most common things you’ll want to do with the weather data you’re collecting is to store it someplace. You’re in luck! With our data.sparkfun.com service, aka Phant, you can store all the weather data on the cloud, for free! You can then pull that data into a multitude of programs and websites to manipulate and visualize your weather data however you like.

This example will show you how to store your weather data on data Phant using the SparkFun Phant Particle Library.

Pushing Data to data.sparkfun.com (Phant)

This example builds off the previous two. You should have the previous four libraries added to your app, as well as a new, fifth library, the SparkFun Phant Particle Library.

alt text

If you’re using Particle Dev, there is a project folder labeled SparkFun-Spark-Phant. Add it to Dev to quickly get started with this example. Open the SparkFun-Spark-Phant.ino example sketch.

You’ll need to create a data.sparkfun.com stream if you have not done so already. Details on how to do that can be found in our tutorial. Keep track our your public and private keys as well as the Field labels you choose.

With that info in hand, open the sketch and find the Phant variables. You’ll need to change these to match your stream’s keys.

alt text

You’ll also need to add each of the Fields you added when you created your stream. Make sure these match exactly.

alt text

What You Should See

With your stream created and the sketch edited accordingly, you can now upload to the Photon. Once complete, you should begin to see data populate on your stream.

alt text

Click for a larger view.

You can now pull that data into any other device or service to organize however you see fit.

Pushing Weather Data to Wunderground

If you would like to upload your weather data to Wunderground, you can follow along with the WIMP Weather Station tutorial to learn how to accomplish the same with your Photon Weather Station.

Example 4: Internet-connected Weather Station

All we’ve learned so far has been to help prepare us for the challenging yet rewarding task of creating your own weather station connect to the Web. This example will build off all the previous examples. We’ll also be adding a Serial Graphic LCD connected to the Weather Shield via a Bluetooth connection so you can collect data online as well as having a monitor indoors that prints live weather data.

Required Materials

To follow along with this example, you’ll need a few more components. There are few different options for creating such a connection.

SparkFun Bluetooth Modem - BlueSMiRF Silver

WRL-12577
$24.95
1
SparkFun Bluetooth Modem - BlueSMiRF Gold

WRL-12582
$34.95
SparkFun Bluetooth Modem - BlueSMiRF HID

WRL-10938
$24.95
1
SparkFun Serial Graphic LCD 128x64

LCD-09351
$36.95
1
SparkFun Serial Graphic LCD 160x128

LCD-08884
$69.95
2

Configure the BlueSMiRFs to connect to one another automatically at 115200 baud. If you need help, we have a BlueSMiRF tutorial that covers that information. Connect one Bluetooth module to the Serial Graphic LCD Backpack, and connect the other to the Weather Shield. The LCD should also be set to 115200 baud.

alt text

A BlueSMiRF connected to the Serial 1 Port using a 6-pin, right angle female header with the outermost pins removed.

alt text

The Serial Graphic LCD Backpack connected to one of our discontinued BlueSMiRF modules with RP-SMA. Fortunately, the range on the BlueSMiRF Gold with Chip Antenna is very powerful.

If you’re using Particle Build, grab all the previous libraries plus a new one, the SparkFun Serial Graphic LCD Particle Library.

alt text

If you’re using Particle Dev, there is a project folder labeled SparkFun-Spark-Phant_LCD. Add it to Dev to quickly get started with this example. Open the SparkFun-Spark-Phant_LCD.ino example sketch.

What You Should See

If everything works out, you should see weather data print out on the LCD as well as post to Phant.

alt text

You now have a Internet-connected weather station! Once you have weather-proofed the electronics, as per our WIMP Weather Station tutorial, place it outside, and take it for a spin.

alt text

Resources and Going Further

Here are a few links that should help with any further questions you may have about the Photon Weather Shield:

And don’t forget about the other Photon shields in our lineup!

SparkFun Photon ProtoShield

DEV-13598
$2.5
SparkFun Photon Wearable Shield

DEV-13328
$4.95
SparkFun Photon Battery Shield

DEV-13626
$12.95
SparkFun Photon Micro OLED Shield

DEV-13628
$19.95
SparkFun Photon IMU Shield

DEV-13629
$24.95

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


ZX Distance and Gesture Sensor Hookup Guide

$
0
0

ZX Distance and Gesture Sensor Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The ZX Distance and Gesture Sensor is a collaboration product with XYZ Interactive. The very smart people at XYZ Interactive have created a unique technology that allows for simple infrared beams to be used to detect an object’s location in two dimensions.

The ZX Sensor is a touchless sensor that is capable of looking for simple gestures in the air above the sensor (e.g. swipe left or right). Additionally, the sensor can also recognize the distance of an object away from the sensor up to about 10 inches (the “Z” axis) and the location of the object from side to side across the sensor in about a 6 inch span (the “X” axis).

The ZX Sensor

Covered in This Tutorial

We can use I2C or UART to communicate with the ZX Sensor. In this tutorial, we will show you how to connect the sensor to an Arduino as well as a computer. The tutorial is divided into the following sections:

Materials Used

In addition to the sensor itself, you will need a few extra components to follow along with the Arduino examples:

If you would like to try the ZX Sensor on a Windows-based PC, you will need an FTDI Breakout:

SparkFun FTDI Basic Breakout - 5V

DEV-09716
$14.95
36

Recommended Reading

There are a few concepts that you should be familiar with before getting started with the ZX Sensor. Consider reading some of these tutorials before continuing:

  • What is an Arduino?– Two of the examples use an Arduino to control the ZX Sensor
  • I2C– I2C is the one of the protocols used by the ZX Sensor
  • Serial Communication– We use serial communications to program the Arduino, view debugging information, and transmit data from the ZX Sensor
  • How to Use a Breadboard– The breadboard ties the Arduino to the ZX Sensor
  • How to Install FTDI Drivers– If you are programming an Arduino or using the ZX Sensor demo app, chances are you will need to use an FTDI

Board Overview

The ZX Sensor works by bouncing infrared (IR) beams of light from the two LEDs on either side off of an object above the sensor. The bounced light returns to the receiver in the center of the sensor, and a microcontroller on the back of the sensor interprets the data. We can read the results using an I2C or UART connection.

Pin Descriptions

The ZX Sensor gives us 2 ports to connect to: I2C and UART.

IMPORTANT: You should only use one of I2C or UART to communicate with the ZX Sensor

ZX Sensor front

Pin LabelDescription
GRNNot used
TXOUART transmit out from the ZX Sensor
RXIUART receive. Not used at this time.
VCC3.3 - 5 V power supply
GNDConnect to ground
BLKNot used, but connected to GND
DRData Ready. High when there is data to be read via I2C
CLI2C clock
DAI2C data

Setting the Jumpers

The ZX Sensor has a couple of jumpers on the back of the board that can be opened or closed with a soldering iron.

ZX Sensor back

I2C Pullups - The ZX Sensor, by default, comes with 4.7 kΩ pull-up resistors on the SDA and SCL I2C lines. Remove the solder on this jumper to disconnect the pull-ups.

I2C Addr - By default, this jumper is open. Close it to change the I2C address of the sensor.

JumperI2C Address
Open0x10
Closed0x11

The Infrared Shields

See those little brass tubes on the LEDs? They are needed to block any IR light going directly from the LEDs (inside the brass tubes) to the receiver (the black domed component in the center of the sensor). We want the light to bounce off an object first.

LED blinders

They are held on with Super Glue. You can remove them, but it might require a bit of acetone. If you plan to mount the ZX Sensors in your own housing, make sure IR light can’t travel directly from the sides of the LEDs to the receiver (i.e. you will want to make your own IR shields).

Hardware Hookup

Add Headers

Solder a row of break away male headers to the 9 headers holes on the board.

Solder headers onto the ZX Sensor

Connect the Breakout Board

For the Arduino examples, we will be using I2C. Connect the breakout board to the following RedBoard pins:

ZX Sensor to Arduino Fritzing diagram

ZX SensorRedBoard
VCC5V
GNDGND
DR2
CLA5
DAA4

Note that we connect the DR pin, but we will only use it in the Arduino: Gesture Example. DR stands for “Data Ready,” which is active high whenever data is ready to be read from the ZX Sensor. We can attach this to an Arduino interrupt so we don’t have to continuously poll the sensor.

ZX Sensor connected to RedBoard

Arduino Library Installation

All of the hard work for the ZX Sensor is being accomplished in the microcontroller on the sensor itself. All we need to do is read the results! We have created an Arduino library to make that even easier for you. Click the button to download the latest version of the ZX Sensor Arduino Library.

Download the ZX Sensor Arduino Library!

Unzip the downloaded file. Follow this guide on installing Arduino libraries to install the files as an Arduino library.

Arduino: ZX Example

Load the ZX Demo

Open up the Arduino program and select File → Examples → SparkFun_ZX_Distance_and_Gesture_Sensor → I2C_ZX_Demo.

I2C ZX Demo

Attach a USB mini cable from your computer to the RedBoard. If you have not previously done so, install the FTDI drivers.

For reference, here is the I2C_ZX_Demo.ino sketch.

Run

Make sure you have the correct serial port selected under Tools → Serial Port and “Arduino Uno” selected under Tools → Board. If you have never used the Arduino IDE before, this turoial should get you started.

Click the Upload button and wait for the program to finish uploading to the Arduino. Select Tools → Serial Monitor to open up the serial terminal. More info on the Serial Terminal can be found here. Note that the Serial Monitor settings are the default settings (9600, 8, n, 1). You should see a couple of messages noting that “ZX Sensor initialization complete.”

ZX Sensor initialization

Hover your hand 4 to 10 inches (10 to 25 cm) above the sensor.

Move your hand above the ZX Sensor

Move your hand around above the sensor, and you should see Z (height above the sensor) and X (position side to side) appear in the serial terminal.

ZX Sensor showing position data

NOTE: Z- and X- data is given as an unsigned integer between 0 and 240 (inclusive).

Arduino: Gesture Example

Load the Gesture Interrupt Demo

In addition to providing Z- and X- axis data about an object, the ZX Sensor is also capable of detecting simple gestures. To see an example of this, open File → Examples → SparkFun_ZX_Distance_and_Gesture_Sensor → I2C_Gesture_Interrupt.

ZX Sensor Gesture Demo

Here is the I2C_Gesture_Interrupt.ino sketch for reference.

Run

Upload the sketch, and open the Serial Monitor. You should see a message stating that initialization is complete.

ZX Sensor Gesture initialization

Start with your hand off to one side (a “side” being the one of the infrared LEDs with the brass covers) about 4 to 10 inches (10 to 25 cm) above the sensor. Swipe your hand horizontally across the sensor so that your hand passes over the one infrared LED and then the next infrared LED.

Move your hand from one side to the other

If you performed the gesture correctly, you should see a message appear in the Serial Monitor.

Performing gestures with the ZX Sensor

NOTE: The "Speed" of the gesture is a measure of how fast the gesture occurred. Note that the lower the number, the faster the gesture occurred (e.g. 3 being very fast and 25 being very slow).

Supported Gestures

Here is a list of the currently supported gestures. Make sure each gesture begins outside of the range of the sensor, moves into the range of the sensor, and ends outside the range of the sensor.

GestureDescription
Right SwipeA swipe from the left side of the board to the right and out of range of the sensor. Make sure that your wrist/arm is not in the sensor's range at the end of the swipe!
Left SwipeA swipe from the right side of the board to the left and out of range of the sensor.
Up SwipeObject starts near the sensor, hovers for at least 1 second, and then moves up above and out of range of the sensor.
No GestureThe sensor could not correctly determine the gesture being performed.

PC: ZX Example

The ZX Sensor, in addition to responding to I2C commands, continually transmits ZX data over its UART port. We can connect an FTDI Breakout directly to the ZX Sensor and read the output. You can use serial applications or the screen command (Linux or Mac) to view the output.

NOTE: You can use either 3.3 V or 5 V FTDI. 5 V gives you a bit better range with the sensor.

If you are on a Windows computer, you can use the demo application (linked below) provided by XYZ Interactive to test the ZX Sensor.

Setup

Connect the FTDI Breakout board to the ZX Sensor. Ensure the pins on the FTDI Brekaout line up with the pins on the ZX Sensor (e.g. GRN connects to GRN and BLK connects to BLK). Connect the FTDI Breakout to your computer with a USB cable.

ZX Sensor connected to FTDI breakout board

Download the ZX Demo application, and unzip it.

Download the ZX Demo Application

Run

Double-click to run the ZX Demo application. Under “Input:” on the right side, drop down the list and select the COM port that corresponds to your FTDI Breakout (if you need a refresher on find the right COM port, check out this section of the Terminal Basics tutorial). You do not need to choose an “Output:” port.

Click Open to connect to the FTDI Breakout.

ZX Sensor demo application

Move your hand around above the sensor, and you should see the red ball move.

Using the ZX Sensor connected to a computer

Try out the other tabs in the application! The Z-Control tab lets your try moving your hand toward and away from the sensor, and the Gestures tab computes a few different gestures based on the Z- and X- data.

Resources and Going Further

After trying the basic ZX and gesture demos, you can try the other examples in the Arduino library. A description of each of the examples is given below:

  • I2C_Gesture_Demo– Poll the sensor over I2C to see if any gestures have occurred.
  • I2C_Gesture_Interrupt– The DR pin will go from low to high when a gesture is detected. This example reads the gesture over I2C and tells the sensor to clear DR.
  • I2C_ZX_Demo– Poll the sensor periodically over I2C for Z- and X- axis data.
  • I2C_ZX_Interrupt– The ZX Sensor will throw DR high whenever valid ZX data is ready.
  • UART_Gesture_DemoNOTE: Gestures over UART are not supported at this time. This demo is a placeholder for the time being.
  • UART_ZX_Demo– Read Z- and X- axis data from a software serial port and display them on the Serial Monitor.

Resources

Here are some additional resources to help you with the ZX Sensor:

Other Tutorials

What will you make with the ZX Sensor? If you need some inspiration, check out these related tutorials:

Connecting Arduino to Processing

Send serial data from Arduino to Processing and back - even at the same time!

Serial Graphic LCD Hookup

Learn how to use the Serial Graphic LCD.

RGB Panel Hookup Guide

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

APDS-9960 RGB and Gesture Sensor Hookup Guide

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

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

Lockitron Hardware Hookup Guide

$
0
0

Lockitron Hardware Hookup Guide a learn.sparkfun.com tutorial

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

Lock It up

The Lockitron Mechanical Assembly from SparkFun is a perfect solution for the DIY home automation or Internet of Things (IoT) enthusiast, whether you want to make your life easier by not awkwardly fumbling with keys or add some extra security in your home with three-factor authentication.

The Lockitron

Lockitron, the company, offers a complete solution that includes the mechanical assembly, embedded electronics that can connect to the Internet via Wifi or your phone over Bluetooth, and apps to control your deadbolt. That is definitely the easy, done solution to your automated locking needs.

But, you’re not here for easy, are you? What we have is the mechanical assembly, including motor and battery pack, to help you complete the automated security in your evil lair. An off-the-shelf solution just won’t cut it.

Covered in This Tutorial

In this guide, we will go over the guts of the Lockitron assembly and show you how to connect it to an Arduino Pro Mini. The Pro Mini, by itself, has no wireless capabilities. How you ultimately control your Lockitron will be up to you, whether it’s a tap sensor or through a WiFi connection.

Materials Used

In addition to the Lockitron Mechanical Assembly, you will need a few additional components:

Recommended Reading

Before getting started with the Lockitron, there are a few concepts that you should be familiar with. Consider reading some of these tutorials before continuing:

Lockitron Overview

Before we connect the Lockitron to anything, we should take a look at its internals to get an idea of what it does. Remove the black, plastic cover, and take a look at the inside.

Lockitron annotated internals

  • Motor Housing - This section contains the motor and gears necessary for rotating the outer ring.
  • Motor Wires - The + and - wires for controlling the motor.
  • Outer Ring - This ring has teeth around the edges so it can be turned via the motor. It also contains a number of “bumps” that the 2 bottom limit switches can use to determine its position. Additionally, it holds the inner ring in place and allows it to freely spin 90º.
  • Inner Ring - The inner ring can freely spin 90º within the outer ring. If the outer ring spins past this 90º stop, the inner ring will begin to spin with the outer ring (in either direction). This free spinning motion allows a user to manually lock and unlock the deadbolt.
  • Rubber Insert - This piece fits over the deadbolt’s thumbturn. It can be removed so that you can install the Lockitron on your door first before fitting the rubber insert onto the thumbturn.
  • Battery Holder - A place to put 4x AA batteries and power the rest of the Lockitron (and possibly your electronics).
  • Battery Wires - These wires (red for + and black for -) connect to the 4x AA batteries.

If you plan to wire up the limit switches (a good idea), now is a good time to remove the battery holder. Unscrew the two black Phillips screws from the bottom of the battery holder (underneath where the batteries would go), and carefully remove the holder.

Limit switches and button hole

  • Limit Switches - There are 4 limit switches that are pressed whenever one of the “bumps” on the rings moves by. The top 2 switches coincide with the “bumps” on the inner ring (orange), and the bottom 2 switches look for “bumps” on the outer ring (black).
  • Button hole - On the original Lockitron, a button stuck out of this hole that allowed you to configure the Lockitron’s wireless properties. Since we don’t have the original electronics, we are going to use the hole to route wires out of the Lockitron housing.

Lockitron annotated limit switches

We are going to assign arbitrary names to the limit switches so that we know what to call them in our code. We also recommend labeling the wires (e.g. with a piece of tape and a pen) that are connected to the limit switches. When we put the battery housing back in the Lockitron, it will be very difficult to see which wire connects to which switch.

  • 1A - First to be hit when the inner ring (orange) spins counterclockwise.
  • 1B - First to be hit when the inner ring (orange) spins clockwise.
  • 2A - First to be hit when the outer ring (black) spins counterclockwise.
  • 2B - First to be hit when the outer ring (black) spins clockwise.

Hardware Hookup

Hook up Wires

We first want to connect a set of wires to the limit switches, motor, and battery compartment. In the end, we should have something like the picture below. The following steps will show you how to get there.

Lockitron annotated wires

Connect Wires to the Switches

Unscrew the battery holder, and set it aside (if you have not done so already). Examine the limit switches.

Lockitron switch annotated

  • COM - Common terminal
  • NO - Normally open. The COM and NO terminals are connected when the switch is engaged.
  • NC - Normally closed. The COM and NC terminals are connected when the switch is not engaged.

Cut, strip, and tin 8x 6-8 inch wires (I used 4 green and 4 yellow wires). Solder them to the outermost terminals on the limit switches. We will be using the COM and NC terminals.

Solder wires to Lockitron limit switches

We recommend you label the wires so you know to which switch it is connected. In this instance, I tagged all the yellow (COM) wires with their respective switch (1A, 1B, 2A, 2B). I plan to connect the green wires (NC) all to ground and the yellow wires (COM) to individual Arduino pins.

Tags on wires for limit switches

Extend the Motor Wires

Cut, strip, and tin another 2x 6-8 inch wires for the motor. Use your favorite wire splicing technique (here are some good ones: 1, 2, 3) to connect to the motor wires. I used red and black to keep with the + and - theme.

Wires to Lockitron motor

Extend the Battery Wires

Once again, cut, strip, and tin another set of wires for the batteries. You will need 2x 6-8 inch wires. Use your favorite splicing technique to connect to the battery wires. I used red and black wires to connect to + and -, respectively.

Wires to Lockitron battery compartment

Route Wires out of the Housing

Carefully pull all the wires through the button opening in the housing.

Routing wires through Lockitron button hole

Solder Headers

Solder headers onto the Pro Mini and Motor Driver board. Don’t forget to add headers to the programming port of the Pro Mini (the part where you attach the FTDI breakout).

Arduino Pro Mini and motor driver board

Attach Everything to a Breadboard

Attach the Pro Mini, Motor Driver board, and 2 buttons to the breadboard. Connect the wires from the Lockitron to the breadboard and add additional wires as shown.

Lockitron Fritzing diagram

Replace Battery Holder

Screw the battery holder back in place, making sure that the limit switch wires do not get caught underneath. Do not add batteries at this time.

Lockitron battery compartment

Example Code

With all of the wires connected, we can upload some code to the Pro Mini.

Example Sketch

Plug in the FTDI breakout to your Pro Mini, and connect a USB cable from it to your computer. Run the code from the Codebender window below, or copy and paste it into your Arduino IDE.

Run

Once the program has successfully uploaded to your Pro Mini, disconnect the FTDI breakout from the Pro Mini. Add 4x AA batteries to the battery holder, and the motor should rotate to a “home” position.

Lockitron controlled with an Arduino

Try pushing the two buttons to mimic the “lock” (top button) and “unlock” (bottom button) functions.

Running the Lockitron Arduino demo code

Installation

The fine folks at Lockitron made a fantastic video showing how to install the Lockitron device. We skipped past the first 1:14 of the video, which shows how to connect the Electric Imp in the housing to WiFi (we don’t need that; we made our own electronics!).

If you want to mount the breadboard next to the Lockitron, you can use the sticky tape on the back of the breadboard or add your own tape/glue.

Lockitron and breadboard mounted on a door

We’re using an RFduino in this picture, but the idea is the same.

Once you have everything working, you can always enclose the electronics for added security.

Resources and Going Further

The Lockitron is a great way to add some advanced technology to your door and venture into the world of home automation. This guide, hopefully, helped show you how to use the Lockitron Mechanical Assembly. From here, the possibilities are endless on how you want to control your door:

Resources

Other Tutorials

Need inspiration on how to interact with the Lockitron? Check out these tutorials:

Bluetooth Basics

An overview of the Bluetooth wireless technology.

SparkFun RFID Starter Kit Hookup Guide

Learn the basics of Radio Frequency Identification (RFID) and how to get started with the SparkFun RFID Starter Kit.

BC118 BLE Mate 2 Hookup Guide

Hooking up and using the BLE Mate 2, which uses the BC118 BLE module from BlueCreations.

ESP8266 Thing Hookup Guide

An overview of SparkFun's ESP8266 Thing - a development board for the Internet of...Things. This tutorial explains the circuitry driving the board, and how to get it up and running in an Arduino environment.

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

ESP8266 WiFi Shield Hookup Guide

$
0
0

ESP8266 WiFi Shield Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The ESP8266 is a popular, inexpensive WiFi/microcontroller system-on-chip (SoC). Although it can be programmed like any microcontroller, the ESP8266’s popularity was gained as a simple, serially-controlled WiFi gateway. Using an AT command set, any microcontroller with a UART can use the ESP8266 to connect to WiFi networks, and interact with the rest of the Internet world over TCP or UDP. It’s an easy (and cheap!) way to get your Arduino on the Internet!

ESP8266 WiFi Shield

There are a variety of designs based around the ESP8266, including tiny, modular boards and more accessible development boards like the SparkFun ESP8266 Thing. The ESP8266 WiFi Shield finds a middle ground between the Module and the Thing – it comes pre-flashed with an AT-command firmware, so it can be controlled by any UART, but it also breaks out and provides command access to all of the ESP8266’s I/O. It comes in the familiar Arduino Shield shape, and should work with any similarly-sized Arduino-compatible development board out there.

Whether you want an introduction to the ESP8266 – without leaving the comfortable hardware confines of your Arduino – or you just have a back-stock of Arduino’s that need an inexpensive gateway to the Internet, the ESP8266 WiFi Shield may meet your needs.

Covered In this Tutorial

This tutorial details the hardware and firmware design behind the ESP8266 WiFi Shield. It also explains how to use the Shield with an Arduino-compatible development board and the Arduino IDE. The guide is broken down into a few sections, which you can navigate around using the bar on the right. Those sections include:

Required Materials

The ESP8266 Shield surrounds the WiFi SoC with everything it should need to operate and connect to a WiFi network. All you need to add to it are headers, some solder, and an Arduino. Here are a list of parts we use in the tutorial, in case you want to follow along:

SparkFun RedBoard - Programmed with Arduino

DEV-12757
$19.95
55
Arduino Stackable Header Kit - R3

PRT-11417
$1.5
10
SparkFun WiFi Shield - ESP8266

WRL-13287
$14.95

Instead of the RedBoard, you should be able to use almost any other Arduino-compatible development board – the Uno or Leonardo for example.

You’ll also need a set of soldering tools, if you don’t already have them. A simple iron and some solder should really be all you need.

Suggested Reading

Before delving headlong into this tutorial, there are a few concepts you should be familiar with. Check out these related tutorials, if their content sounds foreign to you:

  • What is an Arduino?– What is this ‘Arduino’ thing anyway?
  • Arduino Shields– All things Arduino Shields. What they are and how to assemble them.
  • Serial Communication– Asynchronous serial communication concepts: packets, signal levels, baud rates, UARTs and more!
  • How to Solder - Through-hole Soldering– Are you new to electronics and soldering? Have you soldered before but need a refresher? Do you solder all day everyday but still feel you could use a few tips and tricks? This tutorial with cover everything you need to know about through-hole soldering.

Hardware Overview

This section covers the hardware features of the ESP8266 WiFi Shield. Most of the board’s action is on the top side, which should look a little something like this:

alt text

There are a couple features you should be familiar with, before equipping the Shield with headers and plopping it on you Arduino.

Serial Ports – Selectable and Level Shifted

The ESP8266 WiFi Shield features selectable serial lines, which route the RX and TX signals to either the Arduino’s devoted hardware serial port (on pins 0 and 1), or a software serial port on pins 8 and 9. The active port is selected by the on-board switch.

ESP8266 WiFi Shield serial section

The switch’s positions are labeled “SW” and “HW” for “software” and “hardware”; they should be intuitive – slide towards the hardware port for “HW” and towards pins 8 and 9 for “SW”.

Watch out! When you're programming your Arduino (assuming it's an ATmeg328P-based 'duino), make sure the UART select switch is slid over towards the "SW" position. If it's set to "HW", all of those bits and bytes being programmed into the Arduino will also be sent over towards the ESP8266 — there's a chance the spurious data might put the ESP8266 into an unknown (though recoverable) state.

The ESP8266’s default baud rate is set to 9600, so, for most sketches, software serial works fine, and allows the hardware port to be used for debugging. We recommend keeping this switch set to “SW” unless you need those pins for something else, or just have to use hardware serial.

It’s also important to note that the ESP8266’s maximum input voltage is about 3.3V. To avoid any voltage conflict between a 5V Arduino and the ESP8266, the RX and TX signals are level shifted between 5V and 3.3V.

Arduino Reset Button

The shield’s reset button is tied only to the Arduino. Pressing and releasing the button will restart the Arduino, running it’s sketch from the top of the setup() function.

Reset button

Pressing the reset button will have no immediate effect on the ESP8266.

LED Indicators

The WiFi Shield includes two LED indicators: a simple red power indicator and a blue “status” LED. The red power LED should illuminate whenever power is being delivered from the Arduino to the ESP8266 Shield. If you need to debug anything, checking for this LED should be your first step.

LED indicator location

The blue status LED is tied into the firmware of the ESP8266. It’ll blink, be solid, or turn off depending on which state it’s in.

LED StateESP8266 State
OffWiFi disconnected. Not configured.
BlinkingStation mode: ESP8266 attempting to connect to access point.
AP mode: ESP8266 waiting for incoming connections
OnStation mode: ESP8266 connected to access point.
AP mode: Devices connected to ESP8266 AP.

The status LED is tied to GPIO 5 of the ESP8266.

ESP8266 GPIO and Programming Ports

The ESP8266 is a much more than a simple serial-to-WiFi gateway. It’s has almost a dozen I/O that can be configured as digital inputs or outputs – it even has a (relatively limited) ADC! These GPIO are all broken out towards the top-left side of the shield.

GPIO and programming port

The shield’s firmware is equipped with custom commands, which allow your Arduino to set, write, and read to these pins. More on that later.

The ESP8266 WiFi Shield can also be repurposed and reprogrammed through the programming port. Whether you want to add AT commands of your own, or flash custom firmware on the ESP8266, this port may come in very handy later on.

The pinout of the programming port matches our FTDI Basic breakouts. Solder on some male headers, and mate the two boards together to set up the programming interface. More on that later too!

AT Firmware Overview

While the hardware is obviously important, what really makes the WiFi Shield play nicely with an Arduino is its serial-based AT command-set firmware.

The ESP8266 WiFi Shield ships with Espressif’s (the manufacturer of the ESP8266) latest release of their AT command set firmware. We’ve tweaked the base firmware to add support for the status LED and serial control of the ESP8266’s unused I/O. Our firmware is as open source as can be (some of Espressif’s source is only available as blobs) – you can check it out in our ESP8266 WiFi Shield GitHub repository.

Using the AT Command Set

In later parts of this tutorial, we’ll introduce an Arduino library, which handles all of this “AT” stuff for you. But it doesn’t hurt to at least familiarize yourself with the commands used to configure the ESP8266.

The ESP8266's default serial baud rate is 9600 bps. This communication speed can be configured, but slower speeds are recommended if software serial is used.

For the full list of the ESP8266’s AT commands check out this document. There are a variety of commands, which configure everything from access-point names/passwords, to TCP connections, to the device’s baud rate.

alt text

Example page from the AT command set guide – this one demonstrates how to connect to a WiFi access point.

If you’re manually entering these commands, keep in mind that the end of each command should be signaled by a carriage return then line feed (“\r\n”).

As an example exercise, here are a series of commands you might type to connect a WiFi access point and get your IP address:

> AT+CWOMDE=1
    OK> AT+CWJAP="MySSID","MyPSK"
    WIFI CONNECTED
    WIFI GOT IP
    OK> AT+CIFSR
    +CIFSR:STAIP,"192.168.0.101"
    +CIFSR:STAMAC,"18:fe:34:9d:b7:d9"

Custom GPIO Commands

We’ve taken Espressif’s AT command firmware and added a few additional functions which give you control over the ESP8266’s unused digital GPIO. In all, there are 9 GPIO to be digitally controlled: 0, 2, 4, 5, 12, 13, 14, 15, and 16 (XPD).

The custom commands allow you to set a pin to input or output (or input with pullup resistor), digitally write high or low, or read the pin’s state:

FunctionCommandExampleNotes
Pin ModeAT+PINMODE=<pin>,<mode>AT+PINMODE=5,oMode:
  • o: OUTPUT
  • i: INPUT
  • p: INPUT_PULLUP
Digital WriteAT+PINWRITE=<pin>,<state>AT+PINWRITE=5,hState:
  • h: HIGH
  • l: LOW
Digital ReadAT+PINREAD=<pin>AT+PINREAD=0Response: 0 or 1 for LOW or HIGH.

Hardware Assembly

Before you can use the ESP8266 Shield, you’ll need to solder a few headers in so it can interface with your Arduino.

Stackable headers are always a good option for shields, especially if you plan on stacking more shields or plugging in jumper wires.

Stackable headers on Arduino

You can also opt for the more form-factor-friendly male headers, if stacking isn’t as important to you.

Depending on how you’ll use the shield, you can also solder headers into the ESP8266 GPIO and program headers. The programming header can interfere with the bigger USB-B connectors on Arduino Uno’s, so keep their clearance in mind when you’re soldering them in.

ESP8266 WiFi Shield w/ headers soldered to extra GPIO

Female headers can be a good choice for the GPIO header, while right angle male headers make it easy to interface the programming headers with an FTDI breakout.

Antenna Clearance

Unfortunately, the ESP8266 WiFi Shield’s printed PCB antenna can potentially run into interference problems with Arduino ISP headers. After seating the shield on your Arduino, you may want to slightly nudge the shield up, to avoid bumping the board against the 2x3 ISP header.

alt text

The header can interfere with the Shield’s WiFi signal, and lead to lower-than-expected signal sensitivity. If your shield is having trouble connecting to a network, make sure there’s some clearance here.

Tilt shield to avoid ISP header

Installing the ESP8266 AT Library

Let’s get to programming! To make interfacing with the shield’s AT command set as painless as possible, we’ve written a simple Arduino library. You can get the library from our GitHub repository, or download it by clicking the button below.

Download the SparkFun ESP8266 AT Library

We recommend using the latest version of Arduino with this library (currently 1.6.5). For help installing the library check out our Installing an Arduino Library tutorial.

Run the ESP8266_Shield_Demo Example

The SparkFun ESP8266 AT library includes a handful of example sketches, they demonstrate everything from connecting to an access point, to serving up a webpage, to setting up a chat server. To test everything out, load up the “ESP8266_Shield_Demo” example, by going to File>Examples>SparkFun ESP8266 AT>ESP8266_Shield_Demo.

To configure the ESP8266 for your local WiFi network, you’ll need to modify a pair of strings, near the top of the sketch.

language:c
const char mySSID[] = "mySSID";
const char myPSK[] = "myPassword";

Lastly, before uploading the sketch, make sure the UART switch is set to SW– it should always be in this state whenever you upload something new. After verifying the switch is in the correct position, upload away!

This example runs through some of the foundational functions of the ESP8266 AT library. It connects to an AP, finds it’s local IP address, tries to connect to a remote server (example.com) to get a webpage, and finally sets up a server of it’s own.

Opening up the serial monitor (set to 9600 baud), and following along with the instructions (you’ll need to send a few characters to trigger events), will keep you informed on how the Shield is working.

Screenshot example

Once you get to the final, server example of the sketch, try loading up a web browser and navigating to the displayed web address. The ESP8266 should serve up a web page like this:

Browser example

You will need to be on the same network for this to work.

Using the ESP8266 AT Library

The example from the previous section – and the others included with the library – should go a long way towards demonstrating the usage of the SparkFun ESP8266 AT library. This section will document some of the more commonly-used functions. For more documentation check out the library’s GitHub repository.

Initialization

You’ll need to include two libraries at the top of any ESP8266-using Arduino sketch: <SparkFunESP8266WiFi.h> and <SoftwareSerial.h>:

language:c
#include <SoftwareSerial.h> // Include software serial library, ESP8266 library dependency
#include <SparkFunESP8266WiFi.h> // Include the ESP8266 AT library

In your setup(), to initialize the ESP8266 and make sure it’s functioning, call esp8266.begin(). This function will return either true or false, indicating if communication was successful with the ESP8266.

language:c
if (esp8266.begin()) // Initialize the ESP8266 and check it's return status
    Serial.println("ESP8266 ready to go!"); // Communication and setup successful
else
    Serial.println("Unable to communicate with the ESP8266 :(");

esp8266.begin() must be called before any other ESP8266 function.

Setting Up WiFi

To connect your ESP8266 to the local WiFi network, call esp8266.connect(). This function has two parameters: a network SSID and password. For example:

language:c
int retVal;
retVal = esp8266.connect("myNetwork", "myNetworkPassword");
if (retVal < 0)
{
    Serial.print(F("Error connecting: "));
    Serial.println(retVal);
}

The connect() function will also return a value, indicating it’s success. Any value greater than 0 indicates success. Any value less than 0 means there was some trouble connecting.

This function can take some time to complete – the timeout in the library is set to 30 seconds.

After connecting, you can check your local IP address by calling esp8266.localIP(). This function will return a variable of type IPAddress.

language:c
IPAddress myIP = esp8266.localIP(); // Get the ESP8266's local IP
Serial.print(F("My IP is: ")); Serial.println(myIP);

TCP Client

Once you’ve connected to a network, you probably want to interact with the Internet! To use the ESP8266 as a TCP client, use the ESP8266Client class. First, create an object. You can have up to five simultaneous client’s:

language:c
ESP8266Client client; // Create a client object

Once the client is created, you can call the connect() member function to connect to a destination server. This function requires two parameters: a destination server (IPAddress or String) and a destination port.

For example, to connect to sparkfun.com on port 80, after creating the client object call:

language:c
retVal = client.connect("sparkfun.com", 80); // Connect to sparkfun (HTTP port)
if (retVal > 0)
    Serial.println("Successfully connected!");

connect() will return a number greater than 0 on success, and a negative value if it fails.

Once you’ve connected to a server, you can use the standard stream functions to send and receive data. For example, to send an HTTP request use client.print()

language:c
client.print("GET / HTTP/1.1\nHost: example.com\nConnection: close\n\n");

Or to read what the server sends back, use client.available() and client.read():

language:c
while (client.available()) // While there's data available
    Serial.write(client.read()); // Read it and print to serial

Finally, to close a client connection, call client.stop().


The ESP8266 AT Library is capable of even more: you can set up a TCP server, turn the ESP8266 into an access point, for example. Load up one of the other examples in the library to give these other features a try.

(Re-)Programming the ESP8266

The ESP8266 works great and it’s cheap, but it can be so much more than a simple AT-command-driven serial-to-WiFi gateway! It can be reprogrammed just like any microcontroller, and you can even load Arduino sketches onto it.

Danger zone! Uploading new code to the ESP8266 will overwrite the AT command firmware it ships with. You can always put that firmware back on, but the AT library probably won't work with whatever custom code you load onto the ESP8266.

This section is included with this tutorial, in case anyone wants to use the ESP8266 WiFi Shield as more of a general purpose ESP8266 development board. You can skip it if you intend on using the Shield as an actual Arduino Shield.

Programming Hardware

To load code onto the ESP8266 WiFi Shield, you’ll need a couple extra bits of hardware: a 5V FTDI Basic and a wire.

Actually, any device that can translate computer-speak (either USB or RS-232) to TTL serial could work (see the old RS232 Shifter), but the FTDI Basic and it’s FTDI Cable counterpart work best, as they mate directly with the ESP8266 WiFi Shield’s programming header.

SparkFun FTDI Basic Breakout - 5V

DEV-09716
$14.95
37
FTDI Cable 5V

DEV-09718
$17.95
7

You’ll also need a jumper wire to easily connect and disconnect GPIO0 from GND. GPIO0 controls the ESP8266’s run mode – if it’s LOW (0V, GND) when the chip boots up, it starts up its bootloader. If GPIO0 is high on bootup, it’ll begin running its application code.

GPIO0 ValueESP8266 Mode
HIGH (3.3V)Run Program
LOW (0V)Bootloader

There is a pull-up resistor attached to GPIO0, so all you should need to do is pull it to GND when uploading code and leave it floating otherwise. There are a variety of ways to achieve this connection, the easiest of which may be running a male-to-male jumper wire between female headers.

Wire GPIO0 to GND to allow the ESP8266 to enter bootloader mode

If you’re going to be doing a lot of code uploads, perhaps you’ll want to set up a switch between GND and floating.

Installing the Addon With the Arduino Boards Manager

With the release of Arduino 1.6.4, adding third party boards to the Arduino IDE is easily achieved through the new board manager. If you’re running an older version of Arduino (1.6.3 or earlier), we recommend upgrading now. As always, you can download the latest version of Arduino from arduino.cc.

This ESP8266 addon for Arduino is based on the amazing work by Ivan Grokhotkov and the rest of the ESP8266 community. Check out the ESP8266 Arduino GitHub repository for more information.

To begin, we’ll need to update the board manager with a custom URL. Open up Arduino, then go to the Preferences (File>Preferences). Then, towards the bottom of the window, copy this URL into the “Additional Board Manager URLs” text box:

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

If you already have a URL in there, and want to keep it, you can separate multiple URLs by placing a comma between them.

Adding Board Manager URL to Arduino preferences

Hit OK. Then navigate to the Board Manager by going to Tools>Boards>Boards Manager. There should be a couple new entries in addition to the standard Arduino boards. Look for SparkFun ESP8266 Development Boards. Click on that entry, then select Install.

Installing additional boards from Board Manager

The board definitions and tools for the ESP8266 Thing include a whole new set of gcc, g++, and other reasonably large, compiled binaries, so it may take a few minutes to download and install (the archived file is ~110MB). Once the installation has completed, an Arduino-blue “INSTALLED” will appear next to the entry.

Selecting the ESP8266 Board

With the Board addon installed, all that’s left to do is select the proper board from the Tools>Boards menu. Under that menu, find “SparkFun ESP8266 Thing” and select that.

Board selection

Then select your FTDI’s port number under the Tools>Port menu.

Uploading and Running a Sketch

Now that you’ve got the environment set up, it’s time to upload some code. If you’re using an FTDI Basic to upload code, you can also use that board to power the WiFi Shield. Remove the Shield from your Arduino, plug in the FTDI cable, and the power LED should illuminate.

Power the shield via FTDI

Load up a simple blink sketch – setting the blink pin to 5 (attached to the Shield’s STAT LED).

language:c
#define ESP8266_LED 5

void setup()
{
  pinMode(ESP8266_LED, OUTPUT);
}

void loop()
{
  digitalWrite(ESP8266_LED, HIGH);
  delay(500);
  digitalWrite(ESP8266_LED, LOW);
  delay(500);
}

Don’t forget, when you upload a sketch to the ESP8266, to make sure GPIO0 is connected to GND. Viola! You’re on your way to being an ESP8266 developer! For more guidance on ESP8266 development, check out our ESP8266 Thing Hookup Guide, notably the sections starting around the example sketches.

Resources & Going Further

The ESP8266 WiFi Shield is open source hardware, you can find all of our design documents in our ESP8266 WiFi Shield GitHub Repository. In addition to that, these resources may come in handy:

ESP8266 Resources

An awesome community has grown around the ESP8266. We owe them big time for the amazing Arduino addon they’ve cooperatively built. For all of your ESP8266 needs, we recommend checking out the esp8266.com Community Forum. In addition to that, here are a few ESP8266-related resources we’ve found incredibly helpful:

The ESP8266 Thing is open source hardware! If you need, or just want to look at, the PCB design files, you can find them in our ESP8266 Thing GitHub repository.

Going Further

Need a little project inspiration, now that you’ve got your ESP8266 Thing up-and-running? Maybe some of these related SparkFun tutorials will help spur some ideas:

Weather Station Wirelessly Connected to Wunderground

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

Are You Okay? Widget

Use an Electric Imp and accelerometer to create an "Are You OK" widget. A cozy piece of technology your friend or loved one can nudge to let you know they're OK from half-a-world away.

Pushing Data to Data.SparkFun.com

A grab bag of examples to show off the variety of routes your data can take on its way to a Data.SparkFun.com stream.

Using AT&T's M2X With the CC3000

A set of tutorials and examples to show how to connect an Arduino and CC3000 to AT&T's M2X data streams. We show how to post, fetch, and delete data. The final lesson is controlling an LED from an M2X stream.

With it’s deep sleep ability, the Thing is a great foundation for a WiFi-based weather station, or a friendly, huggable, interactive plushy.


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

Building Large LED Installations

$
0
0

Building Large LED Installations a learn.sparkfun.com tutorial

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

Introduction

While designing the layout for the new SparkFun Emporium, I was given the opportunity to design a large LED art installation. I’ve helped build LED installations before, but had never had the opportunity to design one from the ground up. Thus was born the CandyBar, a 46-foot LED bar consisting of 8 meters of addressable LED strips (480 LEDs total), all controlled via a FadeCandy connected to a Raspberry Pi running the FadeCandy server.

alt text

Covered in this Tutorial

Controlling LEDs is one of the most fundamental tasks in embedded electronics, and it’s often the “Hello World” for many beginners starting out on a new platform. However, LED-based projects add up quickly and can become complex very fast. This tutorial is intended to be a guideline for helping you design and build your own large-scale LED installation, while sharing some of the lessons learned from this build.

We’ll go over the planning stage, pointing out considerations that will need to be taken as you design. This section will cover how you plan to control the LEDs, as well as power considerations. Next, we’ll cover the build process. This section will cover how to build in stages for large projects, and how to make your installation transportable if need be. Last, we’ll show the installation process and discuss the next steps to make your installation interactive.

Materials Used

Here is a list of all the SparkFun parts used in this project.

Other parts used in this build include:

No two installations will ever be exactly the same. This list is just here for reference and suggestions. Your vision and budget may vary, resulting in certain parts being added or omitted.

Suggested Reading

The FadeCandy GitHub is definitely the place to start if you’ve opted to use the FadeCandy in your project. There are tons and tons of examples showing how to control it through various means, from C++ and Python code to Processing.

A lot was learned from my friend Dan Julio, who built a very impressive LED installation, Luminescence, for The Dairy Center in Boulder, CO. His controller and driver PCBs were used in this design to ensure the installation would be robust and last as long as the space it’s housed within. More information about these boards can be found on his website.

This FadeCandy LED Curtain tutorial written by Phillip Burgess was also very helpful. Learning how to set up the FadeCandy Server with multiple FadeCandy devices or with an irregular number of LEDs requires altering the configuration file for the server. This tutorial helps clarify how to setup said configuration as well as offering lots of other great tips.

If you need to brush up on some more basic concepts, here are some that pertain to this tutorial.

  • Ohm’s Law& Electric Power - Together, these tutorials teach you how to calculate all the necessary power requirements your LEDs will require.
  • LED Basics - Learn about the finer details pertaining to light-emitting diodes.
  • How to Solder - There’s lots to solder in any installation.
  • Working with Wire - Being a pro at wire splicing and soldering will make the build process much easier.
  • Getting Started with Raspberry Pi - If you’ve never worked with the Pi or similar Single Board Computer before, you may want to check this out.

Planning and Design Phase

The planning and design phase is by far the most important. A well-planned project usually results in an easier build process and execution. Here are some of the considerations you’ll need to make as you plan out your installation:

Addressable or Non-Addressable LEDs

This should be one of the first things you nail down. Led strips typically come in two flavors: addressable or non-addressable. Addressable LED strips, such as this one, are usually the go-to for many art installations. Each individual LED on the strip can be controlled independently of one another via a small microcontroller attached to each LED. Any installation you’ve seen that is displaying images or patterns is most likely using addressable LEDs. The project covered in this guide uses addressable LEDs.

In contrast, there are non-addressable LED strips. These strips are generally cheaper, but they offer much less control. The entire strip can either be on or off, there is no individual LED control, and the entire strip can only be one color at a time. For installations that don’t require the display of many different colors at once, this may be a better option. You could also use a number of these strips and control each strip independently, which would still give you many colors in one area.

Before diving in to the build, it’s a good idea to test each strip individually to avoid complicated troubleshooting down the road. Also worth noting is that these strips can come in different densities, as in amount of LEDs per strip. Be aware of whether you’re using strips with 60 LEDs per meter versus 64 LEDs per meter. This will come into play later on.

Controlling the LEDs and Hardware Limitations

How do you want to control all these LEDs? One of the biggest factors when deciding this is figuring out how many LEDs you want your final installation to contain. Some LED controllers have limitations on how many LEDs they can control. For example, the FadeCandy can handle up to 512 LEDs each. If you have more than 512 LEDs, you’ll need to add a second FadeCandy or use a different driver. More drivers means an added bit of complexity, as you’ll need to keep track of the addresses of each one, as well as each LED’s location.

Only one FadeCandy was used to control the 480 LEDs in the CandyBar. It lives atop the OctoController board from danjuliodesigns.com, and communicates to the Driver boards over varying lengths of Ethernet cables. The Ethernet cables provide both power and communication to each pair of LED strips through the DualDriver boards as well as ESD protection.

Power

This is one area that is often overlooked. A few LEDs draw very little power, but add up several hundred and you have one very power-hungry project. Not only that, but power must be distributed evenly to prevent some LEDs appearing brighter than others or putting off slightly different colors.

For the CandyBar, the same power scheme that Dan used in his Luminescence project was used, scaled for my purposes: a single 24V/250W power supply, which then delivers 5V to each subsequent DualDriver board at up to 30 Watts per pair of LED strips (2x1 meter segments).

If you want to add more LEDs, you will need to add more power. Dan ended up using five of these supplies to power, one for each of the five FadeCandies controlling the 2300 LEDs in the sculpture.

alt text

Image courtesy of danjuliodesigns.com.

You’re not limited to these particular power supplies. If you have high-current 5V supplies, you can power the strips directly from them. Just be aware of how much current you’re drawing from any power supply you use.

Space and Environmental Conditions

How are you going to enclose this project? Is it going to be indoors or outdoors? Does it need to be sealed off from the elements? The answers to these questions can greatly affect how you build your project. If the LEDs need to be sealed up, heat may become an issue. If you’re working indoors, you can save some money by not having to buy tons of weather proofing materials, or products that are already weatherproof.

Luckily for me, the location for the CandyBar had already been picked, and the idea to house the LEDs atop a long ledge covered in decorative molding had been decided before I was brought on to the project. Sometimes it’s easier to design around a set of requirements rather than having free range to design as you see fit.

The CandyBar was built in pieces that could all be disassembled and reassembled atop the ledge. The plan was to use strips of hardboard cut into 8-foot segments. Hardboard is sturdy enough to house LED strips, but lightweight enough that it wouldn’t put strain on the ledge.

I had 8 meters of LED strips to cover the 46-foot ledge. Adding more LEDs meant more power and another FadeCandy, but I wanted to keep this as simple as possible. I didn’t have time to shop for different strips that have the LEDs more widely spaced apart, so I cut the strips into smaller sizes to even out the spacing between sections of LEDs. Each strip ended up getting cut in two, giving me 16 half-meter strips, and making the gaps between each much less noticeable.

As you’re designing, just know that things may look good on paper, but you may have to improvise come build time.

Construction

It’s wise not to start building until you have all the parts you think you’ll need. As you build, you may find a need for parts you didn’t think of during the design phase. Or, as in my case, you may find that you didn’t get enough of a particular material.

The actual assembly and construction is my favorite part. It’s very satisfying to watch your project come to life, piece by piece. In my case, I needed a very long space to work in. All the pieces of hardboard were placed in one long row, just as they would be in the final installment.

Each segment was marked where the LEDs would be attached and where the driver boards would go.

To attach the strips to the driver boards, the opposite ends of the strip that weren’t needed were cut off and connected via screw terminals.

alt text

As planned, some of these connectors ended up near the end of the hardboard sections, making connecting and disconnecting a breeze. However, some of the segments did not line up with the hardboard. These strip segments were affixed with polarized connectors.

alt text

alt text

With everything marked and the LED strips prepped, it was time to adhere the strips and drivers to the hardboard with double-sided tape. Ribbon cable was used to connect the portions of LEDs that didn’t need to be disassembled.

alt text

Once everything was soldered, it was time to test it all out. The FadeCandy server has a nice button to turn all the LEDs on or off for a quick test. With the solder connections all tested, the next task was to figure out the LED mapping.

Setting Up the FadeCandy Server

If you’ve opted to use the FadeCandy, this is a good time to set up the control portion of the project and begin testing your LED strips. This tutorial assumes that you already have you Pi set up and can ssh into it or have it attached to a monitor, keyboard and mouse.

Inside the examples folder of the FadeCandy GitHub, you’ll find a config folder that houses a few different config files for the server. With help from this tutorial, the file below was created for mapping the layout of the CandyBar, which required accounting for the 60 LEDs per strip version I have, versus the 64 LEDs per strips that are set as the default in the file.

{"listen": [null, 7890],"verbose": true,"color": {"gamma": 2.5,"whitepoint": [1.0, 1.0, 1.0]
    },"devices": [
        {"type": "fadecandy","map": [
                [ 0,    0,   0, 60 ],
                [ 0,   60,  64, 60 ],
                [ 0,  120, 128, 60 ],
                [ 0,  180, 192, 60 ],
                [ 0,  240, 256, 60 ],
                [ 0,  300, 320, 60 ],
                [ 0,  360, 384, 60 ],
                [ 0,  420, 448, 60 ]
            ]
        }
    ]
}

Another gotcha is that the mapping assumes you are creating an array of LED strips, like a display, and the CandyBar is just a line of LEDs. Thus every other strip was mapped backward, with strip one mapping from 0-59, and the following going from 119-60. You can account for this in software or in the server config file should your project also be linear in design. I ended up just accounting for it in software. The Python sketch below was great for a quick test.

language:python
#!/usr/bin/env python

# Light each LED in sequence, and repeat.

import opc, time

numLEDs = 480
client = opc.Client('fadecandy.local:7890')

while True:
    for i in range(59, 0, -1):
        pixels = [ (0,0,0) ] * numLEDs
        pixels[i] = (255, 255, 255)
        client.put_pixels(pixels)
        time.sleep(0.01)
    for i in range(60, 119):
        pixels = [ (0,0,0) ] * numLEDs
        pixels[i] = (255, 255, 255)
        client.put_pixels(pixels)
        time.sleep(0.01)
    for i in range(179, 120, -1):
        pixels = [ (0,0,0) ] * numLEDs
        pixels[i] = (255, 255, 255)
        client.put_pixels(pixels)
        time.sleep(0.01)
    for i in range(180, 239):
        pixels = [ (0,0,0) ] * numLEDs
        pixels[i] = (255, 255, 255)
        client.put_pixels(pixels)
        time.sleep(0.01)
    for i in range(299, 240, -1):
        pixels = [ (0,0,0) ] * numLEDs
        pixels[i] = (255, 255, 255)
        client.put_pixels(pixels)
        time.sleep(0.01)
    for i in range(300, 359):
        pixels = [ (0,0,0) ] * numLEDs
        pixels[i] = (255, 255, 255)
        client.put_pixels(pixels)
        time.sleep(0.01)
    for i in range(419, 360, -1):
        pixels = [ (0,0,0) ] * numLEDs
        pixels[i] = (255, 255, 255)
        client.put_pixels(pixels)
        time.sleep(0.01)
    for i in range(420, 479):
        pixels = [ (0,0,0) ] * numLEDs
        pixels[i] = (255, 255, 255)
        client.put_pixels(pixels)
        time.sleep(0.01)

Installation

Once you have all the bits and pieces assembled, it’s time to install them in their permanent (or temporary) resting place. A word of advice: high-up, long installations can be a pain to troubleshoot.

alt text

Each driver is connected and tested after installation.

Heads up! Be careful not to attach any of the Ethernet cables while the system is powered.

alt text

Each cable runs back to the controller board.

alt text

Power cables and an extra long mini-USB cable from the FadeCandy run from the controller board through the ledge, through a wall-mounted cable keeper and attach to the Raspberry Pi and power supply.

alt text

Here’s a block diagram that shows what all the connections look like.

alt text

Click for a larger view.

Once you have everything installed, it’s time to fire it up, and bask in the warming glow of your art.

alt text

Resources and Going Further

I hope this tutorial has given you some ideas for how to take on the task of building a large installation. There are numerous ways to make such an installation interactive, and with the FadeCandy, the control possibilities are seemingly endless. I’ve thought of using accelerometers and/or force sensors to make an LED combat game, à la Dragon Ball. I also intend to make an LED cube, similar to ones I’ve made in the past, that can control the color or patterns of the bar.

If you’d like to learn more about the FadeCandy, check out the links below.

  • FadeCandy GitHub - This repo seriously has a ton of examples and info if you check all the read mes. The
  • Udder - Udder is a lighting control server by Mike Bissell that drives the Fade Candy servers with complex, never repeating patterns.
  • Open Pixel Control (OPC) - OPC is the protocol used to communicate to the FadeCandy in many examples.

For more large art inspiration, check out these tutorials:

Interactive Hanging LED Array

Learn how we converted 72 lightbulbs into an interactive LED array for our conference room.

RGB Panel Jumbotron

This tutorial will show you how to combine a webcam, a 32x32 RGB LED panel, and a Teensy 3.1 to stream video from the webcam, pixelate it, and display it on the LED panel - LIVE.

Hacker in Residence: The Harmonic Skew Zoetrope

Check out Hacker in Residence, Jesse's awesome Harmonic Skew Zoetrope in this project tutorial.

Bare Conductive Musical Painting

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

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

SparkFun Blocks for Intel® Edison - Dual H-Bridge

$
0
0

SparkFun Blocks for Intel® Edison - Dual H-Bridge a learn.sparkfun.com tutorial

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

Introduction

SparkFun’s H-Bridge Block for Edison adds a two-channel low-voltage low-current h-bridge (the Toshiba TB6612) to your stack. The block can be configured to draw power either from the VSYS supply of the stack or from an external supply connected to the header on the block.

H-bridge hero shot

Dual H-Bridge Block

Suggested Reading

If you are unfamiliar with Blocks, take a look at the General Guide to Sparkfun Blocks for Intel Edison.

Other tutorials that may help you on your Edison adventure include:

Board Overview

alt text

Dual H-Bridge Block Functional Diagram

  • Motor Outputs - Two DC motor outputs. Motor A and B

  • Motor Power Input - External power input for DC motors. Limit to 15v DC.

  • VSYS -> VIN - Close this jumper to power Motors off VSYS. Use caution to not overdraw power supply capabilities.

  • Expansion Header - The 70-pin Expansion header breaks out the functionality of the Intel Edison. This header also passes signals and power throughout the stack. These function much like an Arduino Shield.

Using the Dual H-Bridge Block

To use the Dual H-Bridge Block simply attach an Intel Edison to the back of the board or add it to your current stack. Blocks can be stacked without hardware but it leaves the expansion connectors unprotected from mechanical stress.

alt text

Dual H-Bridge Block Installed

We have a nice Hardware Pack available that gives enough hardware to secure three blocks and an Edison.

alt text

Intel Edison Hardware Pack

NOTE: The Dual H-Bridge Block does not have console access or a voltage regulator. It is recommended to use a console communication block in conjunction with this block like ones found in the General Guide to Sparkfun Blocks for Intel Edison.

C++ Code Example

We’re assuming that you’re using the Eclipse IDE as detailed in our Beyond Arduino tutorial. If you aren’t, you’ll need to go to that tutorial to get up to speed.

Getting Started

Follow the instructions in the programming tutorial to create a new project named “SparkFun_H-Bridge_Edison_Block_Example”. Once you’ve created the project, open the project files on disk (hint: you can find the path to the project by choosing “Properites” from the project menu), and copy the three source files found in the Edison H-Bridge Block CPP library GitHub repository into the “src” directory.

Download a zip file of the repository

Hardware Connection

For this example, we have two small DC motors with gearboxes attached to the outputs. The image below shows how to build the circuit. It’s up to you whether you want to drive the motors with an external supply. I’ve shown one here, but I’ve had perfectly good luck closing the supply jumper and pulling the current for these motors directly from the stack’s VSYS rail, even when powering it over USB.

Hookup diagram

Code

Everything you need to know is in the comments.

language:c
#include <unistd.h>

#include "mraa.h"
#include "SparkFun_TB6612_Edison.h"
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{

  // The constructor for the tb6612 class object configures all the necessary
  //  pins, exporting them if they aren't already exported, etc. Note that only
  //  one tb6612 class object may exist at a time, as they share hardware
  //  resources!
  tb6612 motors;

  // The constructor disables the outputs of the tb6612 by asserting the standby
  //  pin on the controller. You *must* use the standby() function to enable
  //  them before proceeding!
  motors.standby(false);

  // diffDrive() accepts a floating point number for channel A and channel B, in
  //  the range -1.0 to 1.0 inclusive.
  motors.diffDrive(0.5,0.5);
  sleep(5);
  motors.diffDrive(-0.5,-0.5);
  sleep(5);

  // "short brake" literally means the two outputs are shorted together. This
  //  drags the motor to a halt in a very short time and then holds it still
  //  (albeit fairly weakly). The shortBrake() function doesn't change the
  //  PWM output settings, so when shortBrake() is released by sending a "false"
  //  parameter, the motor will immediately resume its previous speed.
  motors.shortBrake(true, true);

  // Return the motors to hi-z state. This also doesn't affect the PWM output,
  //  so when standby is released (by passing false to this function) the motors
  //  will immediately resume their former speeds. This also doesn't provide any
  //  braking, so the motors will coast to a stop much more slowly than with
  //  shortBrake().
  motors.standby(true);

  bool brakeA = false;
  bool brakeB = false;
  float dcA = 0;
  float dcB = 0;
  bool onStandby = false;

  // We've provided a number of "get" functions, to check the current status of
  //  the device.

  // getStandby() returns true if the motors are on standby, false otherwise.
  //  This function checks the actual status of the gpio pin used for setting
  //  the standby mode on the chip, so it will always match reality.
  onStandby = motors.getStandby();

  // getDiffDrive() checks the *stored* speed value, rather than the current
  //  value. Thus, if another process alters the PWM output duty cycle without
  //  actually touching the class object, this may return invalid data. It also
  //  doesn't return any information about standby or brake status.
  motors.getDiffDrive(&dcA, &dcB);

  // getShortBrake() checks the pins used for setting the direction/brake mode,
  //  so the values placed into the pointer parameters by the function are
  //  accurate at the time the function is called.
  motors.getShortBrake(&brakeA, &brakeB);

  cout<<"Motor standby status: "<< boolalpha << onStandby << endl;
  cout<<"Motor A brake status: "<< brakeA << endl;
  cout<<"Motor B brake status: "<< brakeB << endl;
  cout<<"Channel A speed: "<< fixed << setprecision(3)<<dcA<<endl;
  cout<<"Channel B speed: "<<dcB<<endl;

  return 0;
}

Resources and Going Further

Now that you have had a brief overview of the Dual H-Bridge Block, take a look at some of these other tutorials. These tutorials cover programming, Block stacking, and interfacing with the Intel Edison ecosystems.

Edison General Topics:

Block Specific Topics:


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

Soil Moisture Sensor Hookup Guide

$
0
0

Soil Moisture Sensor Hookup Guide a learn.sparkfun.com tutorial

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

Getting Started

Have you ever wanted your plants to tell you when they need watered? Or know how saturated the soil in your garden is? With the SparkFun Soil Moisture Sensor, you can do this plus more. This tutorial will show you how to get started using the Soil Moisture Sensor as well as how to build your own soil moisture sensing project.

Soil Moisture Sensor

Soil Moisture Sensor

Required Materials

To follow along with the project at the end of this tutorial, you will need the following:

Suggested Readings

There isn’t much to learning how to use the Soil Moisture Sensor. However, you may find the following concepts useful along the way.

Hardware Overview & Assembly

The Soil Moisture Sensor is pretty straightforward when it comes to hookup. You need to supply VCC and GND. We recommend not powering the sensor constantly to prevent oxidation of the probes (more on this in a bit). You will get a SIG out, which will be between almost VCC and GND, depending on the amount of water in the soil. The two probes are acting as a variable resistor – more water in the soil means better conductivity and results in a lower resistance and a higher SIG out. Your analog readings will vary depending on what voltage you use for Vcc as well as the resolution of your ADC pins.

As for connecting the senor to your circuit, we’ve given you a few different options. You can solder on a 3-pin JST Jumper Wire Assembly if you need to easily switch sensors on your project.

3-pin JST Jumper Wire Assembly

Another option is to solder on a 3-pin 3.5mm Screw Pin Terminal for a slightly more robust connection.

3-pin 3.5mm Screw Pin Terminal

Of course, you can always solder some hookup wire straight to the sensor.

If you intend to use this sensor outdoors, we recommend adding a little protection to the PCB to extend its lifespan. You could always use good ol' fashioned hot glue. However, hot glue does not hold up well in the sun and is only recommended for projects that will not be exposed to high temperatures. For projects that need to be able to withstand all the elements, you could use a conformal coating to cover the SMD parts on the PCB as well as your solder connections.

wires soldered to sensor

Wires have been soldered to this sensor. All the SMD parts and solder joints have then been covered in conformal coating.

Powering the Soil Moisture Sensor

One commonly known issue with soil moisture senors is their short lifespan when exposed to a moist environment. To combat this, we’ve had the PCB coated in Gold Finishing (Electroless Nickel Immersion Gold).

Another way to extend the lifespan of your sensor is to only power it when you take a reading. Using a digital pin set to HIGH on an Arduino, for example, is an easy way to accomplish this. If you wish to power the sensor with more than a digital pin on your microcontroller can provide, you could always use a transistor.

Soil Moisture Sensing Project

For a simple setup that will read and display the water level value, and tell you whether the soil is wet/dry/needs watering, I have hooked the Soil Moisture Sensor to a RedBoard and a Serial Enabled LCD Screen.

SparkFun Soil Moisture Sensor

SparkFun Soil Moisture Sensor

Red (VCC) goes to 5V on the RedBoard, Black (GRN) goes to ground on the RedBoard, and Green (SIG) goes to analog pin 0 on the RedBoard (can be changed in the code).

Sparkfun Soil moisture senor with LCD screen

Along with the soil moisture sensor, I have connected the LCD screen to 5V, ground, and digital pin 2 for serial communication (also can be changed in the code).

This is a good time to mention that if you want to prolong the life of your soil moisture sensor - meaning you don’t want it to corrode as quickly - you can instead hook up VCC to a digital pin and only power it at 5V when you want to take a quick reading, and then turn it off. If you constantly have the soil moisture sensor powered it will corrode over time, and the more water in your soil, the faster that will happen. Another way to protect your soil moisture sensor from corroding is by encasing the probes in gypsum; this allows water from the soil to be detected, but delays corrosion significantly.

Firmware

The code for this is fairly straightforward. You will need the Software Serial library to interact with the serial LCD screen. If you do not have this library you can get it from the Arduino GitHub here. If you have never uploaded a library or want a quick refresher on how to do that, check out our tutorial here.

For more specific information about the code, you can read the comments in the code itself:

language:c
// SparkFun Soil Moisture Sensor and Serial LCD example 1
// By Sarah Al-Mutlaq 2015
// Sketch reads sensor and desplays level and whether soil is wet or dry

// Use the softwareserial library to create a new "soft" serial port
// for the display. This prevents display corruption when uploading code.
#include <SoftwareSerial.h>

// Attach the serial display's RX line to digital pin 2
SoftwareSerial mySerial(3,2); // pin 2 = TX, pin 3 = RX (unused)


// Here we are setting up some water thersholds that we will
// use later. Note that you will need to change these to match
// your soil type and environment.

int thresholdUp = 400;
int thresholdDown = 250;

// We are setting up the pin A0 on the redboard to be our sensor
// pin input:

int sensorPin = A0;


void setup(){
  mySerial.begin(9600); // set up serial port for 9600 baud (speed)
  delay(500); // wait for display to boot up
}

void loop(){
  // Here we are declaring a string, which are lines of words,
  // and we want DisplayWords to be the words displayed on
  // the LCD screen, which will change based on whether the soil
  // wet or dry based on our threshold values above.
  String DisplayWords;

  // We need to set up a pin to get the value that the soil
  // moisture sensor is outputting, so sensorValue will get the
  // analog value from the sensor pin A0 on the redboard that we
  // set up earlier.

  int sensorValue;
  sensorValue = analogRead(sensorPin);

  // move cursor to beginning of first line on LCD:
  mySerial.write(254);
  mySerial.write(128);

  // clear display:
  mySerial.write("");
  mySerial.write("");

  // move cursor to beginning of first line of the LCD screen:
  mySerial.write(254);
  mySerial.write(128);

  //Write what we want to desplay on the screen:
  mySerial.write("Water Level: ");
  mySerial.print(sensorValue); //Using .print instead of .write for values

  // Now we are going to check if the water level is below a
  // out thresholdDown value we set earlier, and if it is have
  // words "Dry, Water it!" display one column over on the first
  // row:

  if (sensorValue <= thresholdDown){
    // move cursor to beginning of second line on LCD:
    mySerial.write(254);
    mySerial.write(192);

    DisplayWords = "Dry, Water it!";
    mySerial.print(DisplayWords);

  // If the value is not below our thresholdDown value we want to
  // check if it is above our thresholdUp value, and if it is
  // change the display words to "Wet, Leave it!":



  } else if (sensorValue >= thresholdUp){
    // move cursor to beginning of second line on LCD:
    mySerial.write(254);
    mySerial.write(192);

    DisplayWords = "Wet, Leave it!";
    mySerial.print(DisplayWords);

  // Otherwise if it is inbetween the two values we want it to
  // the display it had, so if our soil was really wet and drying
  // the words would only change to "Dry, Water it!" when it got to the lower threshold
  // (thresholdDown), but if it was dry and getting wetter the words
  // would only change to "Wet, Leave it!" when it got to the upper
  // threshold (thresholdUp_):

  } else {
    // move cursor to beginning of second line on LCD:
    mySerial.write(254);
    mySerial.write(192);

    mySerial.print(DisplayWords);
  }

  delay(500); //wait for half a second, so it is easier to read
}

This code has different values for an upper threshold and a lower one, so you have a middle zone that could either be wet or dry depending on whether the soil is drying out (coming down from being wet) or getting wet (coming up from being dry). If you don’t want this middle zone, you can set both thresholds to the same value, but I have found that having this middle area is more similar to how soil actually works; there really isn’t a point at which soil goes from being wet to dry. If you are interested in soil and how it reacts to water, you should read up on it; it can be very complicated and interesting.

You will need to adjust the code variables anyway, since this will be unique to your setup, soil type, and how wet you actually want your soil to be. Test out the reading and play around with the values until you find some that fit your needs.

Automating Your Watering

Now that we have a project that reads the soil moisture, we can take it a step further and set up a small self-watering system.

Soil moisture sensor with self watering system

Soil moisture sensor with self-watering system

Using some Actobotics parts…

…and some things I picked up from my local Home Depot (bucket, O rings, and PVC pipe) and Hobby Lobby (Crazy straw, zipties, and glues), as well as a small piece I laser cut, I was able to put together the watering system I wanted.

Parts for soil moiture sensor self watering system

Parts for self-watering system

This is just one of many ways you could hook up a motor to run a self-watering system. Other ways include putting a gear directly into the water and having it rotate fast enough to pull the water up and into the plant. Or you could have the motor running a system somewhat like our Bartendro Dispenser.

alt text

Wiring from RedBoard to motor

Here is the code used (basically the same code with just a few additions for the motor):

language:c
// SparkFun Soil Moisture Sensor and Serial LCD example 2
// By Sarah Al-Mutlaq 2015
// Sketch reads sensor and desplays level and whether soil is wet or dry
// and turns on motor if dry

// Use the softwareserial library to create a new "soft" serial port
// for the display. This prevents display corruption when uploading code.
#include <SoftwareSerial.h>

// Attach the serial display's RX line to digital pin 2
SoftwareSerial mySerial(3,2); // pin 2 = TX, pin 3 = RX (unused)

// We'll be controlling the motor from pin 9.
// This must be one of the PWM-capable pins.
const int motorPin = 9;


// Here we are setting up some water thersholds that we will
// use later. Note that you will need to change these to match
// your soil type and environment.

int thresholdUp = 400;
int thresholdDown = 250;

// We are setting up the pin A0 on the redboard to be our sensor
// pin input:

int sensorPin = A0;


void setup(){
  pinMode(motorPin, OUTPUT); // set pin controlling the motor as an output pin
  mySerial.begin(9600); // set up serial port for 9600 baud (speed)
  delay(500); // wait for display to boot up
}

void loop(){
  // Here we are declaring a string, which are lines of words,
  // and we want DisplayWords to be the words displayed on
  // the LCD screen, which will change based on whether the soil
  // wet or dry based on our threshold values above.
  String DisplayWords;

  // We need to set up a pin to get the value that the soil
  // moisture sensor is outputting, so sensorValue will get the
  // analog value from the sensor pin A0 on the redboard that we
  // set up earlier.

  int sensorValue;
  sensorValue = analogRead(sensorPin);

  // move cursor to beginning of first line on LCD:
  mySerial.write(254);
  mySerial.write(128);

  // clear display:
  mySerial.write("");
  mySerial.write("");

  // move cursor to beginning of first line of the LCD screen:
  mySerial.write(254);
  mySerial.write(128);

  //Write what we want to desplay on the screen:
  mySerial.write("Water Level: ");
  mySerial.print(sensorValue); //Using .print instead of .write for values

  // Now we are going to check if the water level is below a
  // out thresholdDown value we set earlier, and if it is have
  // words "Dry, Water it!" display one column over on the first
  // row:

  if (sensorValue <= thresholdDown){
    // move cursor to beginning of second line on LCD:
    mySerial.write(254);
    mySerial.write(192);

    DisplayWords = "Dry, Water it!";
    mySerial.print(DisplayWords);

    // turns the motor on at a slow speed (0 is stopped, 255 is full speed):
    analogWrite(motorPin, 75);


  // If the value is not below our thresholdDown value we want to
  // check if it is above our thresholdUp value, and if it is
  // change the display words to "Wet, Leave it!":



  } else if (sensorValue >= thresholdUp){
    // move cursor to beginning of second line on LCD:
    mySerial.write(254);
    mySerial.write(192);

    DisplayWords = "Wet, Leave it!";
    mySerial.print(DisplayWords);

    // turns the motor off (0 is stopped, 255 is full speed):
    analogWrite(motorPin, 0);

  // Otherwise if it is inbetween the two values we want it to
  // the display it had, so if our soil was really wet and drying
  // the words would only change to "Dry, Water it!" when it got to the lower threshold
  // (thresholdDown), but if it was dry and getting wetter the words
  // would only change to "Wet, Leave it!" when it got to the upper
  // threshold (thresholdUp_):

  } else {
    // move cursor to beginning of second line on LCD:
    mySerial.write(254);
    mySerial.write(192);

    mySerial.print(DisplayWords);
  }

  delay(500); //wait for half a second, so it is easier to read
}

If you are looking for something on a larger scale for your self-watering system, take a look at our Liquid Pump or our 12V Solenoid Valve for outdoor garden hoses.

Have fun sensing your soil’s moisture and adding a few electronics to your plants!

Resources and Going Further

Interested in sensing more things? Check out some of our other sensors and tutorials!

Pulse Sensor

SEN-11574
$24.95
3
PIR Motion Sensor (JST)

SEN-13285
$9.95
2
Load Sensor - 50kg

SEN-10245
$9.95
Piezo Vibration Sensor - Large

SEN-09196
$2.95

HTU21D Humidity Sensor Hookup Guide

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

H2OhNo!

Learn all about microcontrollers and basic electronics with the H2OhNo! water alarm and development board.

ISL29125 RGB Light Sensor Hookup Guide

A guide to help you integrate the ISL29125 RGB light sensor breakout board into your electronic projects.

MMA8452Q Accelerometer Breakout Hookup Guide

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

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

Adding a Timed Button to a Project

$
0
0

Adding a Timed Button to a Project a learn.sparkfun.com tutorial

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

Introduction

Finished SparkFun timed power button

In this tutorial you will learn how to add an on button that will provide power to your project for an amount of time and then turn off again. We will be using a Solid State Relay (SSR) to deal with AC (alternating current) voltages like what you would see coming out of your wall at your house.

PLEASE DON’T HURT YOURSELF! When dealing with high voltages, and high currents, please be extra careful and take any and all precautions.

Required Materials

If you would like to follow along with this tutorial, you will need the following:

Suggested Readings

Before getting started, you may find some of the concepts below helpful.

Why Have a Timed Power Button?

Saving energy is always a good thing, but some projects have sensitive components that need a bit of a break and would last much longer if they weren’t on all the time.

Some interactive projects should not stay powered on indefinitely. Parts of LEDs (especially RGB LEDs) can burn out, systems can lock up. In SparkFun’s new retail space we have dozens of demos that could benefit from a big button that allows the user to power up the project for 5 minutes then powers down until the next customer walks by. The first project to get this attention is our classic Picture Frame Tetris. We hate leaving this on for 24 hours a day because it wastes power, it doesn’t have a good screen saver mode, and we are worried that the LEDs may burn out over time. This button was designed for that, a simple way to provide power to a project for a short time, only when needed.

Getting Started and Uploading Code

Since the project to which I am adding a timer uses DC (direct current), I could have easily added the timer to regulate the DC voltage using just a simple DC relay switch. Most projects in your home will be running off power from the wall, so this tutorial will focus more on how to regulate the AC voltage and current.

We will start with uploading the code. For this project, I have chosen a 5V Pro Mini. To Program a Pro Mini, you’ll need a 5V FTDI Breakout. If your system is using 3.3V instead of 5V, we also have a 3.3V Pro Mini, and 3.3V FTDI Breakout to match.

To connect the Pro Mini to the FTDI Breakout, all you need to do is solder some right-angle male headers onto the FTDI inputs on the Pro Mini.

Pro Mini with right-angle male headers for the FTDI breakout

Pro Mini with right-angle male headers for the FTDI breakout

Once you have the FTDI breakout plugged into the Pro Mini, you can use a USB to Mini-B Cable to plug it right into your computer.

Open up the Arduino IDE, and upload the example code to your Pro Mini (for specific info on what the code is doing take a look at the comments in the code):

Hardware Hookup

As you can see in the code, we will be hooking up the button to pin 13 of the Pro Mini (this can be changed to any pin in the code) and pin 4, as well as 5V high and Ground to our SSR kit (also can be changed in the code). To connect the Pro Mini, you can either directly solder wires onto the pins, 5V, and ground. Or, you can solder on female headers, and plug wires into those.

Photo of Pro Mini Arduino with headers

Photo of Pro Mini Arduino with headers

Fritzing diagram of button Pro Mini and SSR kit hooked up

Fritzing diagram of button, Pro Mini, and SSR kit hooked up

The SSR kit does not come with all of its parts soldered on, so you will need to assemble it.

SparkFun Solid state relay kit all hooked up

Solid state relay kit all hooked up

This solid state relay kit is rated for a max of 125VAC at 8A, so, for a small-medium size project, this is a fine option. However if your project is going to be pulling more current or voltage you might want to look into a full blown Solid State Relay (SSR), this one can handle 380VAC and 40A!

Warning! That is a lot of current so please, be extra extra careful with those kind of projects.

Since I used a Big Dome Pushbutton, I will also be hooking up the LED inside to Vcc and Ground. The code recognizes that the button is pushed when the pin goes high. This means the button will be pulled low and only go high when the button is pushed (meaning 5V will be connected to the pin the button connects when it is pushed).

Last, the load pins on the SSR kit will be hooked up to one of the wires that are going from your project to the AC power supply (usually the wall).

Photo of SparkFun SSR kit hooked up to an AC to DC power supply

Photo of SparkFun SSR kit hooked up to an AC to DC power supply

To protect the project and make sure that nothing is going to short, I recommend covering everything with electrical tape or Heat Shrink. I also added a fair amount of hot glue to this project to protect all the connections and keep everything in place.

Once everything is hooked up and in place, you can plug your Pro Mini (through the FTDI Breakout) into the wall with a 5V adapter, plug in your connected project, and there you have it! A timed on button for your project!

I cut a few pieces of plywood and glued them together to form a little housing for the button.

Finished timer button in enclosure

Resorces and Going Further

Ready for your next project? Check out some of our other awesome tutorials:

Mario the Magician's Magical Lapel Flower

A guest tutorial from the astonishingly talented [Mario the Magician](http://www.mariothemagician.com/). A step-by-step tutorial to put together your own flower with an awesome video demonstration of its use!

Hacker in Residence: The Harmonic Skew Zoetrope

Check out Hacker in Residence, Jesse's awesome Harmonic Skew Zoetrope in this project tutorial.

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

Lockitron Hardware Hookup Guide

How to connect the Lockitron to an Arduino Pro Mini and control it with 2 buttons.

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


Ludus Protoshield Hookup Guide

$
0
0

Ludus Protoshield Hookup Guide a learn.sparkfun.com tutorial

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

Easy Prototyping with Ludus

The Ludus Protoshield is an Arduino shield designed to make it easier and faster to connect motors and sensors to your Arduino compatible development board. It’s really handy for throwing together remote control rovers and small autonomous robots. This guide will get you up and running with your very own Ludus ProtoShield or Ludus Protoshield Wireless!

Ludus ProtoShield

Required Materials

Aside from the Ludus Protoshield, you will also need something add your shield to. We recommend the SparkFun RedBoard or any other Arduino form factor baords such as the Arduino Uno or the Arduino Leonardo.

One of the main features of the Ludus Shield is to make working with motors easier for those just learning. In order to fully utilize this shield, you’ll also need some motors to drive. Check out our Motors Category for some ideas.

Suggested Reading

You may find some of the following concepts useful before using your Ludus ProtoShield.

Hardware Overview

There are two versions of the Ludus Shield available: SparkFun Ludus ProtoShield and Ludus ProtoShield Wireless! First, let’s have a look at the hardware that they have in common.

H-Bridge

The heart of both versions of the Ludus ProtoShield is an H-Bridge Motor Driver. This allows the ProtoShield to drive two DC motors at once in both directions and even brake electronically. This H-Bridge Driver in particular, the TB6612FNG, is rated up to 1.2A per channel at 13V which means it will drive a fairly beefy hobby motor. This makes it ideal for small rover-style robots and kinetic sculptures.

Watch out! Although the TB6612FNG is rated for 1.2A per channel, we found in testing that the practical limit is about 0.8A on both channels before the driver goes into thermal shutdown. You may be able to remedy this with heatsinks and/or active cooling, but we recommend a continued load below 0.8A for most users.

Another feature that both versions have in common is the addition of power (PWR) and ground (GND) rails alongside the GPIO pins. Not only does this help you to avoid the common inconvenience of running out of GND and PWR pins, but because the pins are arranged with PWR in the center, plugging in servos is a snap! The PWR rail can even be switched between 5V (from the Arduino’s voltage regulator) and Vin using the on board slide switches.

The difference between the two boards is that the standard Ludus ProtoShield includes an I2C header whereas the Ludus ProtoShield Wireless adds to that an XBee socket.

alt text

The I2C header on the standard Ludus ProtoShield is laid out so that you can plug in a device such as a Triple Axis Magnetometer or even the 9DOF Sensor Stick. With these sensors it’s possible to set up a dead reckoning navigation system.

If autonomy isn’t your thing, though, the Ludus ProtoShield Wireless is perfect for setting up XBee based remote control. Simply plug an XBee radio module into the socket on the shield, and you’re ready to transmit wireless data using the common zigbee standard!

Simple Motor Control

In this section, we’ll review how to connect a pair of motors to the Ludus ProtoShield and get them spinning. Before we do that, however, let’s talk a little bit about how we talk to the H-Bridge Driver. If we look at the datasheet for the TB6612FNG we find a table like this:

H-Bridge Logic Table

This table shows the relationship between the input and output pins on the H-Bridge. Each of the two channels requires 3 pins to operate: IN1, IN2 and PWM. By driving the IN pins high or low, you can control the direction of the motor on that channel as well as disengage it completely or even short it end-to-end (like pressing the brakes). The signal that you feed to the PWM pin determines the speed of the motor on that channel. By referencing the table above, we discover that in order to make the motor turn clockwise at 50% speed, we’ll need set IN1 to High, IN2 to LOW and send a 50% PWM signal (that’s analogWrite(pin, 128) in Arduino)

We can look at the silkscreen on the shield itself to find out which Arduino pins are connected to which inputs on the H-Bridge. Once we know that, we can start to write some basic example code to control the driver.

Before anything is going to move, we’ll need to connect a pair of motors. If you’re just starting out with robotics, we suggest the DAGU Hobby Gearmotors which are the same ones that come with our Ardumoto Shield Kit. Solder a pair of jumper wires to each of the gearmotors, and plug them into the A+, A-, B+ and B- headers. The example code also allows you to control a servo, so if you’d like to add a servo, plug it into pin 11.

Now, attach the shield to an Arduino or SparkFun RedBoard and connect a power supply, such as a 9V battery. Once that’s done, we can get the example code loaded onto the Arduino.

Grab the example code from the git repository here, and open it in Arduino. Connect your RedBoard or Arduino over USB, and make sure you have the correct board type and COM port selected. Now press “upload” to send the example code to the board!

If everything went well, you should now be able to open a serial terminal (such as the one built into the Arduino IDE), and type a bunch of “w"s to make the motors turn. This example was really written to be used with terminal programs, which allow you to type directly to the port without having to press return. That way, you can drive the robot by holding down the appropriate keys on your keyboard. My favorite terminal program for this is RealTerm. You can get RealTerm here.

Now that we’ve seen this thing in action, let’s dig through the example code. Understanding how the example code works is the first step towards writing your own!

Understanding the Example Code

The example code for the Ludus ProtoShield is designed to let you control the H-Bridge, as well as a servo attached to pin 11, using serial communication. As with most code, it starts with some basic setup:

language:c
#include <Servo.h>

Servo swivel;

int pwm_a = 3; // Channel A speed
int pwm_b = 6; // Channel B speed
int dir_a0 = 4; // Channel A direction 0
int dir_a1 = 5; // Channel A direction 1
int dir_b0 = 7; // Channel B direction 0
int dir_b1 = 8; // Channel B direction 1

char inbit; // A place to store serial input
int swivelpos = 90; // Servo position

void setup()
{
Serial.begin(9600); // Pour a bowl of serial

swivel.attach(11); // Attach servo to pin 11
swivel.write(swivelpos);

pinMode(pwm_a, OUTPUT); // Set control pins to be outputs
pinMode(pwm_b, OUTPUT);
pinMode(dir_a0, OUTPUT);
pinMode(dir_a1, OUTPUT);
pinMode(dir_b0, OUTPUT);
pinMode(dir_b1, OUTPUT);

draw(); // Draw the driving instructions to the serial terminal

}

As you can see, we started out by including the servo library and creating a servo object called “swivel”. Next, we declare a handful of variables to keep track of which pins are responsible for which functions, and also variables for the servo position and incoming serial characters. The setup() function is where serial communication is initialized, the servo object is attached and the control pins are all set as output devices. Finally, we call the function draw(), which we’ll look at in a minute.

language:c
void loop()
{
if(Serial.available()){ // Wait for serial input
    inbit = Serial.read();
    switch(inbit){ // Switch based on serial in
        case 'w': // Move Forward
    forward(200);
    delay(30);
    shutoff();
    break;
        case 's': // Move Backward
    reverse(200);
    delay(30);
    shutoff();
    break;
        case 'q': // Turn Left while moving forward
    turnL(200);
    delay(30);
    shutoff();
    break;
        case 'e': // Turn Right while moving forward
    turnR(200);
    delay(30);
    shutoff();
    break;
        case 'a': // Spin Left in place
    spinL(200);
    delay(30);
    shutoff();
    break;
        case 'd': // Spin Right in place
    spinR(200);
    delay(30);
    shutoff();
    break;
        case 'x': // Short brake
    brake();
    break;
        case 'z': // Spin servo (on pin 11) left
    servoL();
    break;
        case 'c': // Spin servo (on pin 11) right
    servoR();
    break;
    }
}
}

The main loop of the example code just waits to see input on the serial line and then stores the incoming value and compares it against a list of cases. By scrolling through the switch/case statements, you can see the behavior associated with each serial character. The rest of the code is composed of the various procedures that are called in the main loop. Let’s look at a few of these:

language:c
void draw() // Serial Instructions
{
Serial.println("");
Serial.println(" ------------------------- ");
Serial.println(" |       |       |       | ");
Serial.println(" |   Q   |   W   |   E   | ");
Serial.println(" | turnL |forward| turnR | ");
Serial.println(" ------------------------- ");
Serial.println(" |       |       |       | ");
Serial.println(" |   A   |   S   |   D   | ");
Serial.println(" | spinL |reverse| spinR | ");
Serial.println(" ------------------------- ");
Serial.println(" |       |       |       | ");
Serial.println(" |   Z   |   X   |   C   | ");
Serial.println(" |servo L| brake |servo R| ");
Serial.println(" ------------------------- ");
Serial.println("");
}

This one is pretty straightforward! The draw() procedure is just a bunch of print statements that tell you which keys are attached to which functions.

Finally there are a bunch of procedures that actually set the speed and direction of the motors. These are the functions that you’ll want to borrow for your own code because they wrap up all of the control pin stuff we talked about in the last section into intuitive commands like “forward,” “turn,” and “brake.” All of the motion commands are basically structured the same, for example:

language:c
void forward(int speed) // Move Forward
{
digitalWrite(dir_a0, 0);
digitalWrite(dir_a1, 1);
digitalWrite(dir_b0, 0);
digitalWrite(dir_b1, 1);

analogWrite(pwm_a, speed);
analogWrite(pwm_b, speed);
}

The brake() and shutoff() functions are structured the same as the motion procedures except that in the case of brake(), all of the pins are written high, and in the case of shutoff(), all of the pins are written low. The brake() procedure actually shorts the motor so that it resists turning. The shutoff() function simply shuts off power to the motors so that they come to a rolling stop.

Finally, there are the servo control functions, which increment or decrement the servo position variable before writing it to the servo:

language:c
void servoL() // Spin servo (on pin 11) left
{
if(swivelpos>10){
swivelpos = swivelpos-10;
swivel.write(swivelpos);
}
}

The only kind of clever thing going on here is that we check ahead of time whether we’ve reached the limits of the servo so we can’t increment beyond its range of motion.

Going Wireless

If you have the Ludus ProtoShield Wireless, you can free your project from its USB tether! Do do this, you’ll need a pair of XBee radio modules and an XBee Explorer USB. Even if you’re not familiar with XBee, you should be able to run the example code wirelessly as the radio modules should be configured properly by default. For an introduction to XBee, check out this [SparkFun tutorial. There’s a lot more you can do with XBee than what we’ll cover here.

The first step is to plug an XBee radio into the ProtoShield. The silkscreen on the board shows which orientation it should go. Make sure that the slide switch marked “HW_Ser” and “SW_Ser” is set to “HW_Ser”. This will connect the XBee radio to the hardware serial lines of the Arduino. Next, plug your XBee Explorer into the USB port on your computer, and open the serial terminal program that you were using in the Simple Motor Control section. Open the COM port for the XBee Explorer, and switch the Arduino on.

The example code should now work exactly as it did before, only this time, your serial commands are being sent over the air! What’s happening is that the XBee radio is acting like a wireless serial tunnel. As far as the Arduino knows, there’s a USB cable hooked up to the serial line.

Resources and Going Further

Hopefully by now you’ve built yourself a robot to play with! Getting moving is just the start, though. Check out some of our other robotics tutorials to take your Ludus ProtoShield bot to the next level.


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

nRF24L01+ Transceiver Hookup Guide

$
0
0

nRF24L01+ Transceiver Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

These breakout boards provide SPI access to the nRF24L01+ transceiver module from Nordic Semiconductor. The transceiver operates at 2.4 GHz and with power supplies 3.3V-5V. It has 250kbps, 1Mbps and 2Mbps on-air data-rate options and is applicable for low-power applications.

On-board antenna Breakout

nRF24L01+ Transceiver Breakout: on-board antennna version.

Required Materials

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

Suggested Reading

If you aren’t familiar with the following concepts, we recommend reviewing them before beginning to work with the nRF24L01+ Breakouts.

Hardware Overview

Antenna Options

SparkFun carries two versions of the breakout, listed below.

On-board Chip Antenna

On-board Antenna

SparkFun Transceiver Breakout nRF24L01+ with chip antenna (WRL-00691)

The first version is the SparkFun Transceiver Breakout - nRF24L01+ with chip antenna. The on-board chip antenna allows for a more compact version of the breakout. However, the smaller antenna also means a lower transmission range. Keep that in mind if you plan on mounting this board in an enclosure. The enclosure material may also decrease the range of this board, as you cannot move the antenna outside of any interference. This antenna should be suitable for most applications.

RP-SMA

RP-SMA Antenna

SparkFun Transceiver Breakout - nRF24L01+ with RP-SMA antenna (WRL-00705)

If you need more range in your wireless connection or if you need to move your antenna outside an interference zone, we recommend the RP-SMA antenna version of the breakout. You can learn more about SMA connectors here. This version works with the RP-SMA 2.4GHz antenna and its larger counterpart. Because of the external antenna on this version of the breakout, it has a greater range than the on-board antenna version.

Pins

Labeled Pins

Broken out pins with labels

While the nRF24L01+ IC has 20 pins available, our breakout board simplifies this down to the 8 pins required to get up and running. These pins are the same on both versions of the board. The pins function as follows:

  • GND - Ground
  • IRQ - Interrupt pin. This pin is active LOW.
  • MISO - 3.3V-5V tolerant SPI slave output.
  • MOSI - 3.3V-5V tolerant SPI slave input.
  • SCK - 3.3V-5V tolerant SPI clock.
  • CSN - 3.3V-5V tolerant SPI chip select.
  • CE - 3.3V-5V tolerant chip enable. This pin toggles the nRF24L01+ IC between transmit (TX), receive (RX), standby, and power-down mode.
  • VCC - This is VRAW and is regulated on-board down to 3.3V for the proper functionality of the nRF24L01+. Voltage range on this pin is 3.3V-7V.

Functionality

Transmission Mode

The IC can either work in transmit or receive mode. This mode is determined by both the CE pin state, the PWR_UP register, and the PRIM_RX register. The following chart shows the various configurations.

Transmission Mode Truth Table
ModePWR_UP RegisterPRIM_RX RegisterCE PinFIFO State
RX Mode111-
TX Mode101Data in TX FIFOs. Will empty all levels in TX FIFOs
TX Mode10Minimum 10μs high pulseData in TX FIFOs.Will empty one level in TX FIFOs.
Standby-II101TX FIFO empty.
Standby-I1-0No ongoing packet transmission.
Power Down0---

Hardware Hookup

Solder Connection Points

We recommend soldering headers to the nRF24L01+ board to allow you to prototype your circuit. To avoid interference with the antenna on the nRF24L01+, use right-angle male headers. If you need a review for PTH soldering, check out our tutorial here.

Connect the Wires

Now that you have your headers attached, you can plug in the jumper wires. Connect the Redboard and nRF24L01 as listed.

Redboard → nRF24L01+

  • 3.3V → VCC
  • GND → GND
  • D8 → IRQ
  • D9 → CE
  • D10 → CSN
  • D11 → MOSI
  • D12 → MISO
  • D13 → SCK

Final Circuit

Once you have everything connected, your system should look like the following:

nRF24L01 Hookup

nRF24L01+ Circuit Assembly

Repeat!

Since these are radio modules, you’ll need at least two modules to talk to each other. Duplicate the connections between another Redboard and nRF24L01+ module. Don’t forget to attach the antenna to your nRF24L01+ if you have the RP-SMA version.

Arduino Code

There are a lot of libraries available for this module, but we recommend using the RF24 library, originally written by maniacBug, and updated for Arduino 1.6x by TMRh20.

You can find the most up-to-date version of the library here. Alternatively, you can download this zip and install it into your Arduino IDE libraries folder. If you need help with the library installation, please check out our tutorial.

Download the RF24 Library

Once you have your code properly installed, open up Examples → RF24 → GettingStarted.ino.

Check out the User Configuration section of the code, and make sure you update yours as shown below.

language:c
/****************** User Config ***************************/
/***      Set this radio as radio number 0 or 1         ***/
bool radioNumber = 1;

/* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 9 & 10 */
RF24 radio(9,10);

One radio should have the radioNumber set to 0 and the other should be set to 1.

Upload the code to your Redboards. Once you have them both set up, you can open up two terminals set at 115200 bps, 8-N-1, and you should see the following appear on the terminal.

language:c
RF24/examples/GettingStarted
*** PRESS 'T' to begin transmitting to the other node

Press T in one terminal, press R in the other, and wait until you start seeing your radios communicating! You should see something similar in your terminal.

Terminal Output

Receiver output in the terminal.

Resources and Going Further

Going Further

Now that you have your nRF24L01+ up and running, you can start creating your own awesome wireless projects. There are several other examples in the library – use these to to keep exploring your nRF24L01+ modules or modify them for your own personal projects.

Have a great project done? Let us know - we’d love to see it! If you have any feedback, please visit the comments or contact our technical support team at TechSupport@sparkfun.com.

Additional Resources

Check out these additional resources for more information and other project ideas.

For more wireless fun, check out these other SparkFun tutorials:

Understanding the BC127 Bluetooth Module

SparkFun has two boards using the BC127; here's what you need to know to use them.

Exploring XBees and XCTU

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

nRF24L01+ Transceiver Hookup Guide

A basic getting started guided to the SparkFun Transceiver Breakout - nRF24L01+

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

Single Board Computer Benchmarks

$
0
0

Single Board Computer Benchmarks a learn.sparkfun.com tutorial

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

Introduction

A benchmark is a test used to judge the quality of similar things in a group, at least according to Merriam-Webster.

Raspberry Pi benchmarking

We want to see how various SBCs perform

Many computer enthusiasts use a wide array of benchmarking tools to push their computers to the limits and compare the results. PC gaming fans, in particular, favor 3D graphics benchmarks, such as 3DMark to test their computer’s gaming prowess. A single board computer (SBC) may not have the same computing power as a modern gaming desktop, but it can still be quite useful and powerful in the right situation.

SBC users have myriad uses for their tiny computers, so subjecting them to just one benchmark, such as graphics, would be remiss of us to not take power, CPU, RAM, etc. into account. As a result, we put together a suite of tests that cover a breadth of characteristics of the various SBCs.

Note that benchmarking tools generally do not accurately represent how a user might interact with the computer and instead test only one or two aspects of the computer. Additionally, several factors might influence how the benchmark performs, such as specific versions of libraries (e.g. X11 libraries), compiler options used, and even the version of benchmarking tool used.

We want to test the out-of-box performance of several SBCs, and as such, we try to keep all software as default as possible (vanilla install from the manufacturer’s site or pre-installed on the SBC). We will also try to list which versions of the operating system (OS) and benchmarking tool we used so you can have an idea of where things might differ.

The intent of these tests is to give you an idea of the relative performance among several SBCs. As a result, we don’t have to be very accurate, but we would like to try and be as precise as possible so we can compare relative performance. These tests are more broad than in-depth. Additionally, we can choose to leave out tests that require a graphical user interface (GUI) for modules like the Edison.

Intel Edison module

The Intel® Edison runs Linux but does not have a default GUI

In the Tests section, we will cover the various benchmarking tools used, what they test, and how to install them (should you wish to replicate our results).

Every so often, we will benchmark a set of SBCs. Each “round” will ideally cover a subset of SBC within a generation (e.g. “Round 1” might have the Raspberry Pi 2 where as “Round 2” might have the Raspberry Pi 3).

Recommended Reading

Before delving into the benchmarks, we recommend you become familiar with Linux and some of the command line tools. Additionally, we will be looking at power consumption, so a refresher on electric power might be useful.

The Tests

For the majority of the benchmarks, we rely on a few tests within the Phoronix Test Suite (PTS), which is a free, open-source benchmarking tool for Linux (other operating systems are supported). The slick part about PTS is that it can automatically upload results to Open Benchmarking, which we will use liberally. Open Benchmarking is an online platform where users can store their results from PTS, publicly or privately. The power test is not part of PTS, so we will perform it separately.

Phoronix Test Suite

PTS will handle most of our tests. We first need to make sure the PHP 5 command interpreter is installed. On Debian systems, use:

sudo apt-get update
sudo apt-get install php5-cli

We can then download and install v5.8.1 of PTS:

git clone https://github.com/phoronix-test-suite/phoronix-test-suite/
cd phoronix-test-suite
git checkout v5.8.1
./install-sh
NOTE: You can specify a different install directory by calling ./install-sh NEW_DIR.

To run any of the tests, install it first using the install command with the name of the test followed by calling benchmark and the test name.

phoronix-test-suite install pts/<TEST>
phoronix-test-suite benchmark pts/<TEST>

The test can be selected from any of the profiles listed on the Open Benchmarking Test Profiles page. We will be using only a few of these tests.

NOTE: Unless it is a graphics test, the GUI (e.g. X server) should be shut down. For most SBCs, this can be accomplished by pressing Ctrl+Alt+F1 to get to a different console and entering sudo service lightdm stop.

For example, we can run the Himeno test on a BeagleBone Black Rev C (BBBrC). Once it completes, it will provide a text output of the results, which we can choose to upload to openbenchmarking.org. A link will appear in the console showing you where to find your results (http://openbenchmarking.org/result/1507305-BE-BBBRCDEMO13 in the example below).

BeagleBone Black Rev C finishing the Himeno test

CPU (Single Core)

The backbone of any computer is the ability to execute instructions and perform arithmetic. We will test simple number crunching abilities with the encode-flac test. This simple test times how long it takes the CPU to encode a sample WAV file into a FLAC format.

At this time, the default FLAC encoder only uses one thread, which means we are able to compare single core speeds.

Run the encode-flac test with:

phoronix-test-suite install pts/encode-flac
phoronix-test-suite benchmark pts/encode-flac
PRO TIP: If you choose to upload the results to openbenchmarking.org, you can use the unique ID string to run a comparison on another machine with the same test parameters. For example:phoronix-test-suite benchmark 1507085-BE-SFEEDISON70

CPU (Multi-core)

While testing a single core is great for measuring raw speed, many newer computers (including SBCs) are created with multi-core processors. Having multiple cores allows a computer to run threads simultaneously. If a program is written to be multi-threaded, it can take advantage of more than one core and significantly speed up execution time.

We can measure multi-core performance using the Himeno benchmark. According to Open Benchmarking:

The Himeno benchmark is a linear solver of pressure Poisson using a point-Jacobi method.

If you are masochistically curious what the pressure Poisson equation is, see this.

Run the Himeno benchmark with:

phoronix-test-suite install pts/himeno
phoronix-test-suite benchmark pts/himeno

RAM

Another important feature of a computer is how fast it can read and write to random-access memory (RAM). RAM is great for storing short-term or volatile data. How fast we access that is another useful indicator of system performance.

For RAM, we will use the RAMspeed benchmark. This test is capable of running with a variety of parameters, but we will use the simplest one: copying a bunch of integers to and from RAM. This should hopefully give us an idea of the combined read and write speed.

phoronix-test-suite install pts/ramspeed
phoronix-test-suite benchmark pts/ramspeed

Flash Memory

RAM is great for storing data that requires shorter access times, but hard disk drives (HDDs) allow for non-volatile storage (i.e. we don’t lose the data when power is removed). Most SBCs do not use a true “hard disk” but rely on SD cards or onboard eMMC for non-volatile storage, which we will refer to as “flash memory.”

Like RAM, we can test the performance of the file system and flash memory. The IOzone test reads or writes large amounts of data to the non-volatile memory. We will test both read and write as separate tests using 1 MB blocks and a 2 GB test file (we want the test file to be larger than RAM so our operating system does not cache it in RAM).

phoronix-test-suite install pts/iozone
phoronix-test-suite benchmark pts/iozone

Graphics (2D)

As SBCs become more powerful, they are seeing use as home theater PCs and even low-end gaming machines. Many SBCs come with a version of OpenGL or OpenGL ES to handle graphics.

While we were unable to find a good 3D benchmark that ran well on the SBCs, we can test the computer’s ability to draw simple 2D shapes. We used GtkPerf found within PTS to accomplish this. Specifically, we use the circles drawing test, which times how long it takes to draw a set number (in the thousands) of filled circles in a window. This fairly quick test allows us to compare the relative 2D graphics speed of SBCs.

phoronix-test-suite install pts/gtkperf
phoronix-test-suite benchmark pts/gtkperf

Power Test

Another important factor for SBCs is power consumption. Many users want to leave their SBC running continuously and want to know how much current the SBC will draw. How does it compare, for example, to leaving a light bulb on?

To test power consumption, we created a current logging device, lovingly named the “Current Log-O-Matic,” using an mbed LPC1768, an INA169 Breakout, and a microSD Card breakout.

mbed Current Logomatic

The Current Log-O-Matic

The schematic for the Current Log-O-Matic can be found below and the code can be found on mbed’s site.

Current logger schematic

Schematic for logging current draw with an mbed

The Current Log-O-Matic, on boot, records 10 seconds of measured current use (flowing through the INA169 breakout’s sense resistor) in about 20 ms increments. This information is put into a spreadsheet and the average current over those 10 seconds is computed.

NOTE: We removed the INA169's default RS and replaced it with 2x 1 Ω power resistors in parallel (giving us a total of 0.5 Ω).

We wanted to compute the idle and loaded power consumption. To do that, we booted the SBC under test and logged in to the console using a serial terminal. We disabled any extraneous features such as the GUI (e.g. X Windows), WiFi, and Bluetooth. While idle (doing nothing in the console), we took a voltage measurement at the input of the SBC (we want to test the power usage of the whole board) and ran the Current Log-O-Matic. We computed the average idle power usage with P = V x I using the measured voltage (with the assumption that the voltage did not vary much) and average current.

We repeated the test while the SBC was running the Himeno multi-core CPU test to measure the average current usage under load. The average power consumption was also computed using P = V x I.

Round 1

The Contenders

Raspberry Pi 2 (Model B)

Raspberry Pi 2 - Model B

The Raspberry Pi was created as a cheap platform to teach the basics of computer science to students. It is one of the cheapest and most popular SBCs available. We tested a Raspberry Pi 2 - Model B against other SBCs in this round. Running uname -a gives us the version of Linux:

Linux raspberrypi 3.18.11-v7+ #781 SMP PREEMPT Tue Apr 21 18:07:59 BST 2015 armv7l GNU/Linux

BeagleBone Black - Rev C

BeagleBone Black - Rev C

The BeagleBone Black was created by Texas Instruments as an open source single board computer for the masses. Revision C increased the onboard storage to 4 GB and comes pre-loaded with a Debian Linux image. The version of Linux used in the tests was:

Linux beaglebone 3.8.13-bone47 #1 SMP Fri Apr 11 01:36:09 UTC 2014 armv7l GNU/Linux

Intel® Edison

Intel Edison

The Intel® Edison is a tiny computer module intended for wearable devices. Without a video out port, it may not meet the definition of “single board computer.” However, because it is capable of running Linux, we can compare its performance against other SBCs, with the exception of the graphics tests. The version we tested was running:

Linux edison 3.10.17-poky-edison+ #1 SMP PREEMPT Wed Apr 29 03:54:01 CEST 2015 i686 GNU/Linux

pcDuino3

pcDuino3

The pcDuino is LinkSprite’s version of a Raspberry Pi and Arduino mashup. The pcDuino is capable of running Linux and emulating an Arduino at the same time. Note that we ran the OS from a microSD card and not a disk drive connected to the SATA port. We tested version 3, which was running:

Linux ubuntu 3.4.79+ #12 SMP PREEMPT Mon Jul 21 13:05:42 CST 2014 armv7l armv7l armv7l GNU/Linux

Acadia

LinkSprite Acadia

LinkSprite created the Acadia to bring higher-performing ARM CPUs to the SBC market. The Acadia is built around the powerful Freescale i.MX6 processor. Note that we ran the OS from a microSD card and not a disk drive connected to the SATA port. The Linux version was:

Linux Acadia 3.0.35-2666-gbdde708 #76 SMP PREEMPT Tue Feb 10 23:03:49 PST 2015 armv7l armv7l armv7l GNU/Linux

Specifications

For a quick comparison, we have provided some tables showing the various features of the SBCs under test.

Table: CPU and GPU

DeviceProcessorArchitectureCPU SpeedCoresGPU
Raspberry Pi 2Broadcom BCM2836ARM Cortex-A7900 MHz4Broadcom
BeagleBone Black Rev CTI Sitara AM335xARM Cortex-A81 GHz1PowerVR SGX530
Intel EdisonIntel Atom Z34XXSilvermont x86500 MHz2None
pcDuino3Allwinner A20ARM Cortex-A71 GHz2Mali-400MP2
AcadiaFreescale i.MX6ARM Cortex-A91.2 GHz4Vivante GC2000

Table: RAM and Storage

DeviceRAM SizeRAM TypeOnboard StorageFlash Slot
Raspberry Pi 21 GBLPDDR2NonemicroSD
BeagleBone Black Rev C512 MBDDR34 GBmicroSD
Intel Edison1 GBLPDDR34 GBNone
pcDuino31 GBDDR34 GBmicroSD
Acadia1 GBDDR3NonemicroSD

Table: Ports, Connectivity, and Price

DeviceUSBSATAAudio OutHDMIEthernetWiFiBluetoothGPIOPrice
Raspberry Pi 2YesNoYesYesYesNoNo17$39.95
BeagleBone Black Rev CYesNoNoYesYesNoNo66$54.95
Intel EdisonYesNoNoNoNoYesYes40$49.95
pcDuino3YesYesYesYesYesYesNo22$59.95
AcadiaYesYesYesYesYesNoNo22$119.95

The Results

And now for the part you have been waiting for: the results! We will present a comparison chart for each test. You will also be able to find a link to the raw test results in each section should you desire more details.

CPU (Single Core)

Times how long it takes to convert a .WAV audio file to a FLAC file. The raw test results can be found here.

enclode-FLAC results

CPU (Multi-Core)

Computes floating point operations per second (in MFLOPS) by timing how long it takes to solve a pressure Poisson equation. The raw test results can be found here.

Himeno results

RAM

Tests aggregate RAM read and write speed. The raw test results can be found here.

RAMspeed results

Flash Memory

Transfers files to and from flash memory to compute the read and write rates. The raw test results can be found here and here.

Note that the BeagleBone Black Rev C test was slightly different, as we had to use a 512 MB test file (instead of the 2 GB file used for the other tests). There was simply not enough space on the BeagleBone Black’s onboard eMMC.

IOzone results

Graphics (2D)

Times how long it takes to draw a set number of filled circles (many thousands) in a window. The raw test results can be found here.

Note that we left out the Edison as it does not have a video out port and therefore no default GUI.

GtkPerf results

Power

Compute average power consumption based on measured current draw (averaged over 10 seconds) and measured DC voltage. The raw test results can be found here.

Power results

Conclusion

Which SBC is the “best” really depends on what you want to do with it. RAM speed might be important in some applications whereas graphics capabilities might be more important in others. When looking at purchasing a single board computer, do not neglect the importance of physical board size and community support, which were not covered in these tests.

If you have questions or comments on the tests (or just want to talk about single board computers!), please leave them in the Comments Section.

Resources


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

SparkFun Blocks for Intel® Edison - Pi Block

$
0
0

SparkFun Blocks for Intel® Edison - Pi Block a learn.sparkfun.com tutorial

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

Introduction

The Pi Block breaks out and level shifts several GPIO pins from the Intel Edison. It presents them in the same configuration as a Raspberry Pi Model B.

Intel Edison Pi Block

Pi Block

Suggested Reading

If you are unfamiliar with Blocks, take a look at the General Guide to Sparkfun Blocks for Intel Edison.

Other tutorials that may help you on your Edison adventure include:

Board Overview

Annotated Pi Block functions

Pi Block Functional Diagram

  • USB Power - used to provide 5V to Pi Block and power the Edison. Note that the data lines are not connected to the Edison.

  • Power Button - The power switch is connected to the “PWRBTN” line on the Edison. This give the user the ability to place an Edison in sleep or power down the module completely. This does not affect power to other Blocks in the stack.

  • Power LED - The power LED illuminates when power is present on VSYS. This can come from the onboard USB Power or any other powered Block in the stack.

  • Expansion Header - The 70-pin Expansion header breaks out the functionality of the Intel Edison. This header also passes signals and power throughout the stack. These function much like an Arduino Shield.

  • LED Jumper - If power consumption is an issue, cut this jumper to disable the power LED.

  • VSYS Jumper - By default, a USB cable must be attached to the USB Power port to provide power to the 5V pins on the RPi B Header. You can power the Edison and Pi Block from another Block (e.g. Base Block), but there will not be 5V on the pins labeled “5V”. By closing this jumper, you can power the Edison and Pi Block from another Block, and ~4.2V (VSYS) will appear on the pins labeled “5V”.

  • RPi B Header - Same configuration as the old Raspberry Pi Model B pinout.

Using the Pi Block

To use the Pi Block, attach an Intel® Edison to the back of the board, or add it to your current stack. Blocks can be stacked without hardware, but it leaves the expansion connectors unprotected from mechanical stress.

Edison installed on Pi Block

Edison installed on Pi Block

We have a nice Hardware Pack available that gives enough hardware to secure three blocks and an Edison.

alt text

Intel Edison Hardware Pack

NOTE: It is recommended to use a console communication block in conjunction with this block like ones found in the General Guide to Sparkfun Blocks for Intel Edison. Once you have the Edison configured, you can remove the console communication block, power the Edison from the Pi Block, and SSH into the Edison.

You can put headers on the Edison side, which gives you easy access to the pin labels. Note that this pinout is mirrored from the Raspberry Pi Model B pinout.

Headers on top of Edison Pi Block

Headers on Edison side

Alternatively, you can populate the back side of the Pi Block with headers. This method gives the same pinout as a Raspberry Pi Model B. You could, in theory, swap the Edison in for your Raspberry Pi on an existing project, or use Raspberry Pi accessories (e.g. Pi Wedge).

Headers on bottom of Edison Pi Block

Or put headers on the back side of Pi Block

Using the Pi Block as an output device

If you want to use the Pi Block to control high power LEDs or relays, an external transistor or MOSFET will be required. It is possible to illuminate a small LED directly from the level shifter. It may not be as bright since the current output of the TXB0108 level converter is very low (~5ma).

alt text

Connection Diagram for Load (LED, Motor, or Relay)

In the terminal, we will demonstrate how to activate and use a GPIO pin as an output.

First navigate to the GPIO directory on the Edison.

cd /sys/class/gpio

Select the GPIO pin to enable. In this case, we used GPIO 14, which is labeled “GP14” on the Pi Block.

echo 14 > export

Navigate to the newly created GPIO directory.

cd gpio14

If you type “ls”, you should see a bunch of variables.

active_low  direction   power       uevent
device      edge        subsystem   value

Let’s set the “direction” of the port to output

echo out > direction

To confirm this, we will “cat” the value

cat direction

You should see the “out” in the command line. Now the device is configured as an output.“value” is where the status of the pin is set, 1 for high, 0 for low.

echo 1 > value

Testing with a multi-meter, small led, or oscilloscope, you should see a “high” status (3.3V) present on gpio14.

Using the GPIO Block as an input device

If you want the Pi Block to read switches, buttons, or other logic level inputs, you must pay attention to pull-up and pull-down resistors. The level converter on board is very weak. Here are two scenarios explained:

alt text

Connection Diagram for Active High Push Button

alt text

Connection Diagram for Active Low Push Button

In the terminal, we will demonstrate how to activate and use a GPIO pin as an input configured as an active high.

First, navigate to the GPIO directory on the Edison.

cd /sys/class/gpio

Select the GPIO pin to enable. In this case let us use GPIO 14.

echo 14 > export

Navigate to the newly created GPIO directory.

cd gpio14

If you type “ls”, you should see a bunch of variables.

active_low  direction   power       uevent
device      edge        subsystem   value

Let’s set the “direction” of the port to output.

echo in > direction

To confirm this, we will “cat” the value.

cat direction

You should see the “in” in the command line. Now the device is configured as an input.“value” is where the status of the pin is set, 1 for high, 0 for low.

cat value

With a button pressed, you should see a 1. When the button is not pressed you should see a 0. Using the up arrow, you can recall previously run commands.

C++ Examples

We’re assuming that you’re using the Eclipse IDE as detailed in our Beyond Arduino tutorial. If you aren’t, you’ll need to go to that tutorial to get up to speed.

Hardware Connection

Hardware support for this library is simple; one basic red LED and one momentary pushbutton. We’re using a 2N3904 NPN transistor to drive the LED, however, as the drive strength of the outputs on the Pi Block is quite weak. As you can see in the diagram, you’ll also need a couple of 1kΩ resistors and a single 330Ω resistor.

Intel Edison Pi Block connections

While we’ve used GPIO45 and GPIO46 in this example, this code can be used with any of the pins on the Pi breakout. The GPIO to MRAA pin map can be found in the Resources and Going Further section.

Code

Follow the instructions in the programming tutorial to create a new project named “SparkFun_Pi_Block_Example”. Once you’ve created the project, open the “SparkFun_Pi_Block_Example.cpp” file and replace all the existing code with the code block below.

language:c
  /****************************************************************
  Example file for SparkFun Pi Block Support

  14 Jul 2015- Mike Hord, SparkFun Electronics
  Code developed in Intel's Eclipse IOT-DK

  Modified on July 30, 2015 by Shawn Hymel, SparkFun Electronics

  This code requires the Intel mraa library to function; for more
  information see https://github.com/intel-iot-devkit/mraa

  This code is beerware; if you use it, please buy me (or any other
  SparkFun employee) a cold beverage next time you run into one of
  us at the local.
  ****************************************************************/

#include "mraa.hpp"

#include <iostream>
#include <unistd.h>

using namespace mraa;
using namespace std;

int main()
{

  // Oddly, GPIO pin assignment numbers when using the MRAA libraries are not
  //  the same as those inside the operating system. Thus, while we're using
  //  pin 46 as far as the OS is concerned to drive the LED, we're using pin 32
  //  as far as MRAA is concerned. The cheat sheet for that can be found here:
  //  https://github.com/intel-iot-devkit/mraa/blob/master/docs/edison.md
  Gpio LEDPin(45);
  LEDPin.dir(DIR_OUT);

  // Now do a quick little flicker.
  LEDPin.write(0);
  usleep(100000);
  LEDPin.write(1);
  usleep(100000);
  LEDPin.write(0);

  // Alternatively, we can declare the pin in "raw" mode, which has a slightly
  //  different and more unwieldy constructor.
  Gpio buttonPin(32, true, true);
  buttonPin.dir(DIR_IN);

  // In this infinite loop, we'll blink the LED once whenever someone presses
  //  the button.
  while (1)
  {
    // We *know* that if the IO pin reads as 0, or is low, read() returns zero.
    //  However, if it's high, it *may* return something else; the only guarantee
    //  is that it will be nonzero. Thus, don't test to see if a read() returned
    //  a 1!!!
    if (buttonPin.read() == 0)
    {
      LEDPin.write(1);
      sleep(1);
      LEDPin.write(0);
      sleep(1);
    }
  }

  return MRAA_SUCCESS;
}

Additional Examples

Because this block is just a GPIO access device, the existing MRAA GPIO examples can be used with it.

Example projects in the IDE

When you create a new project in the Eclipse IDE, it will offer you the option of several starter projects. Some of them, noted above, are good examples of using the MRAA GPIO functions. They’re more complex than what we’ve provided here, however.

For full documentation of the C++ API for GPIO pins, please visit the official MRAA documentation.

Resources and Going Further

Pin Map

You might have noticed that we used GP46 in hardware and GPIO 32 in our example code. This is because the MRAA library uses a different number for the pins. If you would like to use MRAA to control hardware, figure out which GPIO pins you plan to use on the table below (labeled “Edison Pin”) and then use the MRAA Number in software.

The available pins on the Pi Block have been highlighted in yellow in the table.

Notes:

  • Input/output voltage on the Pi Block is 3.3V
  • Input/output voltage on the GPIO Block is 3.3V by default
  • Input/output voltage on the Arduino Breakout is 5V
  • Input/output voltage on the Mini Breadboard is 1.8V

MRAA pin map table based on Intel’s IOT Dev Kit Repository

Edison Pin (Linux)Arduino BreakoutMini BreakoutMRAA NumberPinmode0Pinmode1Pinmode2
GP123J18-7 20GPIO-12PWM0
GP135J18-1 14GPIO-13PWM1
GP14A4J19-9 36GPIO-14
GP15J20-7 48GPIO-15
GP19J18-6 19GPIO-19I2C-1-SCL
GP20J17-8 7GPIO-20I2C-1-SDA
GP27J17-7 6GPIO-27I2C-6-SCL
GP28J17-9 8GPIO-28I2C-6-SDA
GP4013J19-10 37GPIO-40SSP2_CLK
GP4110J20-10 51GPIO-41SSP2_FS
GP4212J20-9 50GPIO-42SSP2_RXD
GP4311J19-11 38GPIO-43SSP2_TXD
GP44A0J19-4 31GPIO-44
GP45A1J20-4 45GPIO-45
GP46A2J19-5 32GPIO-46
GP47A3J20-5 46GPIO-47
GP487J19-6 33GPIO-48
GP498J20-6 47GPIO-49
GP77J19-12 39GPIO-77SD
GP78J20-11 52GPIO-78SD
GP79J20-12 53GPIO-79SD
GP80J20-13 54GPIO-80SD
GP81J20-14 55GPIO-81SD
GP82J19-13 40GPIO-82SD
GP83J19-14 41GPIO-83SD
GP84J20-8 49GPIO-84SD
GP109J17-11 10GPIO-109SPI-5-SCK
GP110J18-10 23GPIO-110SPI-5-CS0
GP111J17-10 9GPIO-111SPI-5-CS1
GP114J18-11 24GPIO-114SPI-5-MISO
GP115J17-12 11GPIO-115SPI-5-MOSI
GP1282J17-14 13GPIO-128UART-1-CTS
GP1294J18-12 25GPIO-129UART-1-RTS
GP1300J18-13 26GPIO-130UART-1-RX
GP1311J19-8 35GPIO-131UART-1-TX
GP134J20-3 44
GP135J17-5 4GPIO-135UART
GP165A5J18-2 15GPIO-165
GP1826J17-1 0GPIO-182PWM2
GP1839J18-8 21GPIO-183PWM3

Edison General Topics:

Block Specific Topics:


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

microSD Sniffer Hookup Guide

$
0
0

microSD Sniffer Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The microSD Sniffer is a useful tool for hacking or debugging circuits with microSD functionality.

microSD Sniffer

The Sniffer allows you to see the SPI signals passing back and forth from your microSD card to your microcontroller or project.

Covered in This Tutorial

This tutorial will show you how to setup the sniffer as well as how to use it to “sniff” the data transmitted to and received from a microSD card.

Materials Required

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

You will also need a project that has a microSD slot involved. We will be using the microSD Shield and Redboard.

SparkFun RedBoard - Programmed with Arduino

DEV-12757
$19.95
56
SparkFun microSD Shield

DEV-12761
$14.95
4

You will also need some kind of logic analyzer. You can use anything like the following:

Logic Pro 8 - USB Logic Analyzer

TOL-13196
$479.95
Logic 4 - USB Logic Analyzer

TOL-13195
$109.95
1
USB Oscilloscope - MSO-28

TOL-11219
$334.95
USB Oscilloscope - MSO-19

TOL-09263
$269.95

Suggested Reading

If you aren’t familiar with the following concepts, we recommend reviewing them before beginning to work with the microSD Sniffer.

Hardware Overview

Hardware wise, the microSD Sniffer is pretty simple and straight-forward! There’s only 3 main parts you need to be aware of.

Front of Sniffer

Front view of the microSD Sniffer.

1. Headers

The pins of the SD card are broken out for a standard 0.1-inch row of header holes. This allows you to solder headers onto the board and connect into a breadboard for prototyping. Alternatively, you can also just connect IC hooks on these holes and use a logic analyzer or oscilloscope to monitor the traffic across the SPI bus.

2. microSD Socket

This is your standard microSD socket. It fits microSD cards. Hurray simplicity!

3. microSD Insert

Back of Sniffer

Back view of the microSD Sniffer.

These are the actual connection pins for the microSD Sniffer. You will plug these into your circuit in place of where you would normally plug in a microSD card. Notice how they look exactly like the bottom of your microSD card?

Hardware Hookup

Assembly

We’ll be using the microSD Sniffer to see the SPI traffic between the microSD shield and the microSD card. If you aren’t sure how to set up the microSD shield, please review our tutorial here.

Insert the microSD card into the microSD Sniffer socket, and plug the end of the microSD Sniffer into the socket on the microSD shield.

Everything is now ready to go, but we still need something to actually watch the traffic. For this, we will be using the Logic 4 - USB Logic Analyzer. You can use whatever analyzer you have around, but you will need one with 8 channels.

Pair one channel from the analyzer to one header on the microSD Sniffer. Repeat this until all of your headers have been connected to the analyzer. Keep in mind that your analyzer may have a dedicated GND line or other dedicated channels, so make sure you match any of those up if that’s the case.

General Circuit Hookup

Everything is connected and ready to go!

Once everything is connected, it’s time to power it all up and watch the SPI traffic!

Functionality

Visualization

We can now view the data on the SPI bus with the logic analyzer. In our example, the Redboard is running the Examples>SD>Datalogger.ino sketch included by default in the Arduino IDE.

Open up the logic analyzer software, and configure it for your set up. In our example, we’ve labeled each channel with the corresponding pin name on the microSD Sniffer.

The analyzer collects 1 million samples at 8MHz. Once it has collected data, you should see something similar to the following.

Default Reading

Initial Display of Readings

We can see there is definitely something occuring on several of the lines, but it’s still not clear what. If we look at our time scale, the range shown is 0ms to ~35ms. We can zoom in on a smaller time scale to get more detail about the communication occurring.

ZoomedIn

There is much more readable data at the smaller timeframe of 100us displayed.

Looking at our data, we can see something is not quite right – according to the VCC line, there’s no power going to our system! While the issue in this case was only due to a loose connection between the IC hook on the analyzer and the Sniffer, you could dig deeper into each signal to debug your circuit if there is a problem. If we fix the loose connection, the data looks better, showing a HIGH signal on VCC.

->VCC Fixed<-

Again, this is a very simplified example, but you could use the Sniffer to verify the clock signal to your card, or to see if there are actual data signals being sent to the microSD card.

Resources and Going Further

Going Further

Now that you’ve successfully worked with your microSD Sniffer, you can use this to debug any project that uses microSD cards, or hack the communication protocol between system and SD card.

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

Additional Resources

Check out these additional resources for more information and other project ideas.


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

LSM9DS1 Breakout Hookup Guide

$
0
0

LSM9DS1 Breakout Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The LSM9DS1 is a versatile, motion-sensing system-in-a-chip. It houses a 3-axis accelerometer, 3-axis gyroscope, and 3-axis magnetometer – nine degrees of freedom (9DOF) in a single IC! Each sensor in the LSM9DS1 supports a wide range of…ranges: the accelerometer’s scale can be set to ± 2, 4, 8, or 16 g, the gyroscope supports ± 245, 500, and 2000 °/s, and the magnetometer has full-scale ranges of ± 2, 4, 12, or 16 gauss. The IMU-in-a-chip is so cool we put it on a quarter-sized breakout board.

LSM9DS1 with quarter for scale

The LSM9DS1 is equipped with a digital interface, but even that is flexible: it supports both I2C and SPI, so you’ll be hard-pressed to find a microcontroller it doesn’t work with.

Covered In This Tutorial

This tutorial is devoted to all things LSM9DS1. We’ll introduce you to the chip itself, then the breakout board. Then we’ll switch over to example code, and show you how to interface with the board using an Arduino and our LSM9DS1 Arduino library.

The tutorial is split into the following pages:

Required Materials

This tutorial explains how to use the LSM9DS1 Breakout Board with an Arduino. To follow along, you’ll need the following materials:

Example hookup

The LSM9DS1 is a 3.3V device! Supplying voltages greater than ~3.6V can permanently damage the IC. As long as your Arduino has a 3.3V supply output, and you're OK with using I2C, you shouldn't need any extra level shifting. But if you want to use SPI, you may need a level shifter.

A logic level shifter is required for any 5V-operating Arduino (UNO, RedBoard, Leonardo, etc). If you use a 3.3V-based ‘duino – like the Arduino Pro 3.3V or 3.3V Pro Mini– there is no need for level shifting.

Suggested Reading

If you’re not familiar with some of the concepts below, we recommend checking out that tutorial before continuing on.

LSM9DS1 Overview

The LSM9DS1 is one of only a handful of IC’s that can measure three key properties of movement – angular velocity, acceleration, and heading – in a single IC.

The gyroscope can measure angular velocity– that is “how fast, and along which axis, am I rotating?” Angular velocities are measured in degrees per second– usually abbreviated to DPS or °/s. The LSM9DS1 can measure up to ± 2000 DPS, though that scale can also be set to either 245 or 500 DPS to get a finer resolution.

An accelerometer measures acceleration, which indicates how fast velocity is changing – “how fast am I speeding up or slowing down?” Acceleration is usually either measured in m/s2 (meters per second per second) or g’s (gravities [about 9.8 m/s2]). If an object is sitting motionless it feels about 1 g of acceleration towards the ground (assuming that ground is on earth, and the object is near sea-level). The LSM9DS1 measures its acceleration in g’s, and its scale can be set to either ± 2, 4, 8, or 16 g.

Finally, there’s the magnetometer, which measures the power and direction of magnetic fields. Though they’re not easily visible, magnetic fields exist all around us – whether you’re holding a tiny ferromagnet or feeling an attraction to Earth’s magnetic field. The LSM9DS1 measures magnetic fields in units of gauss (Gs), and can set its measurement scale to either ± 4, 8, 12, or 16 Gs.

By measuring these three properties, you can gain a great deal of knowledge about an object’s movement and orientation. 9DOF’s have tons and tons of applications. Measuring the force and direction of Earth’s magnetic field with a magnetometer, you can approximate your heading. An accelerometer in your phone can measure the direction of the force of gravity, and estimate orientation (portrait, landscape, flat, etc.). Quadcopters with built-in gyroscopes can look out for sudden rolls or pitches, and correct their momentum before things get out of hand.

Axis labels for the LSM9DS1 IC

Axis orientations of the LSM9DS1 IC. Note the IC’s polarity-marking dot (for some reason they rotated the magnetometer in the datasheet).

The LSM9DS1 measures each of these movement properties in three dimensions. That means it produces nine pieces of data: acceleration in x/y/z, angular rotation in x/y/z, and magnetic force in x/y/z. The LSM9DS1 Breakout has labels indicating the accelerometer and gyroscope axis orientations, which share a right-hand rule relationship with each other. Note that, according to the datasheet, the x and y axes of the magnetic sensor are flipped (the image above is copied from the datasheet).

The LSM9DS1 is, in a sense, two IC’s smashed into one package – like if you combined an LSM6DS3 accel/gryo with an LSM303DLMTR accel/mag. One half of the device takes care of all-things gyroscope and accelerometer, and the other half manages solely the magnetometer. In fact, a few of the control pins are dedicated to a single sensor – there are two chip select pins (CS_AG for the accel/gyro and CS_M for the mag) and two serial data out pins (SDO_AG and SDO_M).

Choose Your Own Adventure: SPI or I2C

In addition to being able to measure a wide variety of movement vectors, the LSM9DS1 is also multi-featured on the communication interface end. It supports both SPI and I2C, so you should have no difficulty finding a microcontroller that can talk to it.

SPI is generally the easier of the two to implement, but it also requires more wires – four versus I2C’s two.

Because the LSM9DS1 supports both methods of communication, some pins have to pull double-duty. The Serial Data Out (SDO) pin for example, does just that for SPI mode, but if you’re using the device over I2C it becomes an address selector. The chip select (CS_M and CS_AG) pins activate SPI mode when low, but if they’re pulled high the device assumes I2C communication. In the section below we discuss each of the LSM9DS1’s pins, watch out for those pins that support both interfaces.

For much more detailed information about the IC, we encourage you to check out the datasheet!

Breakout Board Overview

Now that you know everything you need to about the LSM9DS1 IC, let’s talk a bit about the breakout board it’s resting on. On this page we’ll discuss the pins that are broken out, and some of the other features on the board.

The Pinout

In total, the LSM9DS1 Breakout breaks out 13 pins.

Top image

The bare-minimum connections required are broken out on the left side of the board. These are the power and I2C pins (the communication interface the board defaults to):

Pin LabelPin FunctionNotes
GNDGround0V voltage supply
VDDPower SupplySupply voltage to the chip. Should be regulated between 2.4V and 3.6V.
SDASPI: MOSI
I2C: Serial Data
SPI: Device data in (MOSI)
I2C: Serial data (bi-directional)
SCLSerial ClockI2C and SPI serial clock.

The remaining pins are broken out on the other side. These pins break out SPI functionality and interrupt outputs:

Pin LabelPin FunctionNotes
DENGyroscope Data EnableMostly unknown. The LSM9DS1 datasheet doesn't have much to say about this pin.
INT2Accel/Gyro Interrupt 2INT1 and INT2 are programmable interrupts for the accelerometer and gyroscope. They can be set to alert on over/under thresholds, data ready, or FIFO overruns.
INT1Accel/Gyro Interrupt 1
INTMMagnetometer InterruptA programmable interrupt for the magnetometer. Can be set to alert on over-under thresholds.
RDYMagnetometer Data ReadyAn interrupt indicating new magnetometer data is available. Non-programmable.
CS MMagnetometer Chip SelectThis pin selects between I2C and SPI on the magnetometer. Keep it HIGH for I2C, or use it as an (active-low) chip select for SPI.
HIGH (1): SPI idle mode / I2C enabled
LOW (0): SPI enabled / I2C disabled.
CS AGAccel/Gyro Chip SelectThis pin selects between I2C and SPI on the accel/gyro. Keep it HIGH for I2C, or use it as an (active-low) chip select for SPI.
HIGH (1): SPI idle mode / I2C enabled
LOW (0): SPI enabled / I2C disabled.
SDO MSPI: Magnetometer MISO
I2C: Magnetometer Address Select
In SPI mode, this is the magnetometer data output (SDO_M).
In I2C mode, this selects the LSb of the I2C address (SA0_M)
SDO AGSPI: Accel/Gyro MISO
I2C: Accel/Gryo Address Select
In SPI mode, this is the accel/gryo data output (SDO_AG).
In I2C mode, this selects the LSb of the I2C address (SA0_AG)

Power Supply

The VDD and GND pins are where you’ll supply a voltage and 0V reference to the IC. The breakout board does not regulate this voltage, so make sure it falls within the allowed supply voltage range of the LSM9DS1: 2.4V to 3.6V. Below is the electrical characteristics table from the datasheet.

Electrical characteristics

The communication pins are not 5V tolerant, so they’ll need to be regulated to within a few mV of VDD.

Another very cool thing about this sensor is how low-power it is. In normal operation – with every sensor turned on – it’ll pull around 4.5mA.

Communication

CS_AG, CS_M, SDO_AG, SDO_M, SCL, and SDA are all used for the I2C and SPI interfaces. The function of these pins depends upon which of the two interfaces you’re using.

If you’re using using I2C here’s how you might configure these pins:

  • Pull CS_AG and CS_M HIGH. This will set both the accel/gyro and magnetometer to I2C mode.
  • Set SDO_AG and SDO_M either HIGH or LOW. These pins set the I2C address of the gyro and accel/mag sensors.
  • Connect SCL to your microcontroller’s SCL pin.
  • Connect SDA to your microcontroller’s SDA pin.
  • The board has a built-in 10kΩ pull-up resistor on both SDA and SCL lines. If that value is too high, you can add a second resistor in parallel to divide the pull-up resistance down (another 10kΩ in parallel, for example, would create an equivalent 5kΩ resistance).

Or, if you’re using SPI:

  • Connect CS_AG and CS_M to two individually controllable pins on your microcontroller. These chip-selects are active-low – when the pin goes LOW, SPI communication with either the accel/gyro (CS_AG) or magnetometer (CS_M) is enabled.
  • SDO_AG and SDO_M are the serial data out pins. In many cases you’ll want to connect them together, and wire them to your microcontroller’s MISO (master-in, slave-out) pin.
  • Connect SCL to your microcontroller’s SCLK (serial clock) pin.
  • Connect SDA to your microcontroller’s MOSI (master-out, slave-in) pin.

Interrupts

There are a variety of interrupts on the LSM9DS1. While connecting up to these is not as critical as the communication or power supply pins, using them will help you get the most out of the chip.

The accelerometer- and gyroscope-specific interrupts are INT1 and INT2. These can both be programmed to interrupt as either active-high or active-low, triggering on events like data ready or when an acceleration or angular rotation exceeds a set threshold.

DRDY and INTM are devoted magnetometer interrupts. DRDY will go low when new magnetometer readings are available. INTM is a little more customizable – it can be used to trigger whenever magnetic field readings exceed a threshold on a set axis.

The Jumpers

Flipping the LSM9DS1 breakout over reveals a trio of two-way, surface mount jumpers. Each of these jumpers comes closed. Their purpose is to automatically put the LSM9DS1 into I2C mode.

Jumpers on breakout

The three two-way jumpers on the back of the board. Follow the labels to see which pin they pull up.

Each of these jumpers pulls a pair of pins up to VDD, through a 10kΩ resistor. The middle pad of the jumper connects to the resistor, and the edge pads connect to a pin (follow the labels to find out which one). You can see how those jumpers match up on the schematic:

Jumpers on schematic

The top jumper connects CS_AG and CS_M to a pull-up – this’ll set the LSM9DS1 to I2C mode. The middle jumper pulls up SDO_AG and SDO_M, which sets the I2C address of the chip. Finally, the far-left jumper adds pull-up resistors to the I2C communication pins – SDA and SCL.

The intention of these jumpers is to make it as easy-as-possible to use the board; using as few wires as possible. If you’re using the breakout with I2C, you can ignore the four SDO and CS pins.

To disable any of these jumpers, whip out your handy hobby knife, and carefully cut the small traces between middle pad and edge pads. Even if you’re using SPI, though, the jumpers shouldn’t hinder your ability to communicate with the chip.

Hardware Assembly

On this page we’ll discuss assembly hints. There’s really not much to assembling the breakout board – the real key is solderingsomething into the breakout holes.

Solder Something

To get a solid electrical and physical connection to the LSM9DS1 Breakout, you’ll need to solder either connectors or wires to the break-out pins. What, exactly, you solder into the board depends on how you’re going to use it.

If you’re going to use the breakout board in a breadboard or similar 0.1"-spaced perfboard, we recommend soldering straight male headers into the pins (there are also long headers if you need ‘em).

I2C and power pins soldered

If you’re only going to use the I2C interface – and ignore the interrupts – you can get away with soldering just the four-pin header.

If you’re going to mount the breakout into a tight place, you may want to opt for soldering wires (stranded or solid-core) into the pins.

Mounting the Breakout

Because the LSM9DS1 senses motion, it’s important (for most applications, at least) to keep it pinned in place. So the boards have four mounting holes toward the corners. The drill holes are 0.13" in diameter, so they should accommodate any 4/40 screw.

LSM9DS1 Breakout dimensions

Consult the EAGLE PCB design files to find out more about the Breakout’s dimensions.

Hardware Hookup

The LSM9DS1 will work over either I2C or SPI. Here are some example wiring diagrams, demonstrating how to wire up each interface.

I2C Hardware Hookup

Out-of-the-box, the board is configured for an I2C interface, as such we recommend using this hookup if you’re otherwise agnostic. All you need is four wires!

i2c fritzing hookup

Connecting the LSM9DS1 to a RedBoard via I2C.

This hookup relies on all of the jumpers on the back of the board being set (as they should be, unless they’ve been sliced). If the jumpers have been cut, connect all four CS and SDO pins to 3.3V.

No level shifters even though the Arduino’s I/O pins are 5V? Well, I2C is a funny interface: pins aren’t directly pulled high by a GPIO, instead an open-drain MOSFET relies on pull-up resistors to create a logic high. Because the breakout board pull-up resistors are stronger (less resistance) than the Arduino’s internal pull-ups, the voltage on the logic pins will be much closer to 3.3V (though a little higher) than 5V – within a tolerable range. Just make sure you power the breakout off of the Arduino’s 3.3V power rail!

SPI Hardware Hookup

For the SPI hookup, we’ll use the Arduino’s hardware SPI pins – 11 (MISO), 12 (MOSI), and 13 (SCLK) – in addition to two digital pins of your choice (for the chip selects). If you’re using a 3.3V Arduino, like the 3.3V/8MHz Pro Mini, you can hook the microcontroller pins directly up to the LSM9DS1.

SPI hookup

If you’re using a 5V Arduino, you’ll also need to grab a level shifter to keep the SPI signals within the tolerable voltage range. You could use the SparkFun Bi-Directional Logic Level Converter for example:

Logic level shifter

(Unless you enjoy wire-tangles, the I2C or 3.3V SPI hookups are recommended.)

Installing the Arduino Library

We’ve written a full-featured Arduino library to help make interfacing with the LSM9DS1’s gyro, accelerometer, and magnetometer as easy-as-possible. Visit the GitHub repository to download the most recent version of the library, or click the link below:

Download the SparkFun LSM9DS1 Arduino Library

For help installing the library, check out our How To Install An Arduino Library tutorial. You’ll need to move the SparkFun_LSM9DS1_Arduino_Library folder into a libraries folder within your Arduino sketchbook.

The LSM9DS1_Basic_I2C Example

To verify that your hookup works, load up the LSM9DS1_Basic_I2C example by going to File>Examples>LSM9DS1 Breakout>LSM9DS1_Basic_I2C. (If you’re using the SPI hookup, load the LSM9DS1_Basic_SPI example instead.)

The default values set by this sketch should work for a fresh, out-of-the-box LSM9DS1 Breakout – it assumes all of the jumpers on the backside are closed. Upload the sketch, then open up your serial monitor, setting the baud rate to 115200. You should see something like this:

Example serial monitor output

The current reading from each axis on each sensor is printed out, then those values are used to estimate the sensor’s orientation. Pitch is the angle rotated around the y-axis, roll is the board’s rotation around the x-axis, and heading (i.e. yaw) is the sensor’s rotation around the z-axis. Try rotating the board (without pulling out any wires!) to see how the values change.

Using the Arduino Library

To help demonstrate the library’s functionality, a handful of examples are included which range from basic to more advanced. To begin to get a feel for the library’s API, try loading up some of the other examples. The comments at the top of the sketch will instruct you on any extra hookup that may be required to use interrupts or other features.

On this page we’ll quickly run down some of the more basic, fundamental concepts implemented by the library.

Setup Stuff

To enable the library, you’ll need to include it, and you also need to include the SPI and Wire libraries:

language:c
#include <SPI.h> // SPI library included for SparkFunLSM9DS1
#include <Wire.h> // I2C library included for SparkFunLSM9DS1
#include <SparkFunLSM9DS1.h> // SparkFun LSM9DS1 library

Make sure the SPI and Wire includes are above the “SparkFunLSM9DS1” (even though you’ll only be using one of the two interfaces).

Constructor

The constructor creates an instance of the LSM9DS1 class. Once you’ve created the instance, that’s what you’ll use to control the breakout from there on. This single line of code is usually placed in the global area of your sketch.

The constructor should be left without any parameters:

language:c
// Use the LSM9DS1 class to create an object. [imu] can be
// named anything, we'll refer to that throught the sketch.
LSM9DS1 imu;

Setting Up the Interface

The LSM9DS1 has tons of settings to be configured. Some are minute, others are more critical. The three most critical settings we’ll need to configure are the communication interface and the device addresses. To configure these values, we’ll make calls to the IMU’s settings struct.

Here’s an example that sets the IMU up for I2C mode, with the default (high) I2C addresses:

language:c
// SDO_XM and SDO_G are both pulled high, so our addresses are:
#define LSM9DS1_M   0x1E // Would be 0x1C if SDO_M is LOW
#define LSM9DS1_AG  0x6B // Would be 0x6A if SDO_AG is LOW
...
imu.settings.device.commInterface = IMU_MODE_I2C; // Set mode to I2C
imu.settings.device.mAddress = LSM9DS1_M; // Set mag address to 0x1E
imu.settings.device.agAddress = LSM9DS1_AG; // Set ag address to 0x6B

Alternatively, if you’re using SPI mode, the imu.settings.device.mAddress and imu.settings.device.agAddress values become the chip select pins. For example, if you’re using SPI mode with CS_AG connected to D10 and CS_M connected to D9, your setting configuration would look like this:

language:c
imu.settings.device.commInterface = IMU_MODE_SPI; // Set mode to SPI
imu.settings.device.mAddress = 9; // Mag CS pin connected to D9
imu.settings.device.agAddress = 10; // AG CS pin connected to D10

Configuring any value from the imu.settings.device can’t take place in the global are of a sketch. If you get a compilation error, like 'imu' does not name a type, you may have those in the wrong place – put them in setup().

begin()-ing and Setting Sensor Ranges

Once you’ve created the LSM9DS1 object, and configured its interface, call the begin() member function to initialize the IMU.

The begin() function will take the settings you’ve adjusted in the previous step, and attempt to communicate with and initialize the sensors. You can check the return value of begin() to verify whether or not the set up was successful – it will return 0 if something goes wrong.

language:c
if (!imu.begin())
{
    Serial.println("Failed to communicate with LSM9DS1.");
    Serial.println("Looping to infinity.");
    while (1)
      ;
}

Once begin() has returned a success, you can start reading some sensor values!

Reading and Interpreting the Sensors

What good is the sensor if you can’t get any data from it!? Here are the functions you’ll need to get acceleration, rotation speed, and magnetic field strength data from the library.

readAccel(), readGyro(), and readMag()

These three functions – readAccel(), readGyro(), and readMag()– poll the LSM9DS1 to get the most up-to-date readings from each of the three sensors.

The read functions don’t take any parameters, and they don’t return anything, so how do you get that data? After the function runs its course, it’ll update a set of three class variables, which will have the sensor data you desire. readAccel() will update ax, ay, and az, readGyro() will update gx, gy, and gz, and readMag() will update mx, my, and mz. Here’s an example:

language:c
imu.readAccel(); // Update the accelerometer data
Serial.print(imu.ax); // Print x-axis data
Serial.print(", ");
Serial.print(imu.ay); // print y-axis data
Serial.print(", ");
Serial.println(imu.az); // print z-axis data

An example of reading and printing all three axes of accelerometer data.

Those values are all signed 16-bit integers, meaning they’ll range from -32,768 to 32,767. That value doesn’t mean much unless you know the scale of your sensor, which is where the next functions come into play.

calcAccel(), calcGyro(), and calcMag()

The library keeps track of each sensor’s scale, and it implements these helper functions to make translating between the raw ADC readings of the sensor to actual units easy.

calcAccel(), calcGyro(), and calcMag() all take a single parameter – a signed 16-bit integer – and convert to their respective units. They all return a float value, which you can do with as you please.

Here’s an example of printing calculated gyroscope values:

language:c
imu.readGyro(); // Update gyroscope data
Serial.print(imu.calcGyro(imu.gx)); // Print x-axis rotation in DPS
Serial.print(", ");
Serial.print(imu.calcGyro(imu.gy)); // Print y-axis rotation in DPS
Serial.print(", ");
Serial.println(imu.calcGyro(imu.gz)); // Print z-axis rotation in DPS

Setting Sensor Ranges and Sample Rates

Some of the more commonly altered attributes in the IMU are the sensor ranges and output data rates. These values can be configured, once again, by setting a value in the settings struct.

For example, to set the IMU’s accelerometer range to ±16g, gyroscope to ±2000 °/s, and magnetometer to ±8 Gs, do something like this:

language:c
imu.settings.accel.scale = 16; // Set accel range to +/-16g
imu.settings.gyro.scale = 2000; // Set gyro range to +/-2000dps
imu.settings.mag.scale = 8; // Set mag range to +/-8Gs
imu.begin(); // Call begin to update the sensor's new settings

The output data rates are a bit more abstract. These values can range from 1-6, where 1 is the slowest update rate and 6 is the fastest.

Resources & Going Further

Hopefully that info dump was enough to get you rolling with the LSM9DS1. If you need any more information, here are some more resources:

Going Further

Now that you’ve got the LSM9DS1 up-and-running, what project are you going to incorporate motion-sensing into? Need a little inspiration? Check out some of these tutorials!

  • Dungeons and Dragons Dice Gauntlet– This project uses an accelerometer to sense a “rolling the dice” motion. You could swap in the LSM9DS1 to add more functionality – like compass-based damage multipliers!
  • 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.
  • Leap Motion Teardown– An IMU sensor is cool, but image-based motion sensing is the future. Check out this teardown of the miniature-Kinect-like Leap Motion!
  • Pushing Data to Data.SparkFun.com– Need an online place to store your IMU data? Check out data.sparkfun.com! This tutorial demonstrates how to use a handful of Arduino shields to post your data online.

Leap Motion Teardown

Let's see what's inside the amazing new Leap Motion input device!

Dungeons and Dragons Dice Gauntlet

A playful, geeky tutorial for a leather bracer that uses a LilyPad Arduino, LilyPad accelerometer, and seven segment display to roll virtual 4, 6, 8, 10, 12, 20, and 100 side dice for gaming.

Are You Okay? Widget

Use an Electric Imp and accelerometer to create an "Are You OK" widget. A cozy piece of technology your friend or loved one can nudge to let you know they're OK from half-a-world away.

Pushing Data to Data.SparkFun.com

A grab bag of examples to show off the variety of routes your data can take on its way to a Data.SparkFun.com stream.

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

8-Pin SOIC to DIP Adapter Hookup Guide

$
0
0

8-Pin SOIC to DIP Adapter Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The SparkFun 8-Pin SOIC to DIP Adapter is a small PCB that lets you adapt SOIC packages into a DIP footprint. These are useful for modding and upgrading devices that use 8-pin DIP ICs, when the upgraded IC is only available in a SOIC footprint. You can also use it for prototyping, to make SOIC packages compatible with solderless breadboards.

SOIC Adapter Array

The updated version of this adapter comes as a small array of PCBs – if you’re adapting one chip, you’re likely to adapt more than one. The PCBs easily snap apart, resulting in four individual boards.

The SOIC land pattern on the board has also been improved from its predecessor. The pads are very long, in order to accomodate both narrow and wide packages. The SOIC lands are staked down with plated through-holes, to prevent lifting during rework. The SOIC is also contained entirely within the DIP outline, for situations with no extra clearance around the IC.

Old Vs. New

Suggested Reading

Check out any of the links below, if you are unfamiliar with a given topic.

Assembly

Assembling the adapter is fairly straightforward, but there are a couple of tricks that make it easier.

Materials

To build up an adapter, you’ll need the following pieces.

Tools

The following tools are also recommended.

Building An Adapter

Snap Boards Apart

The array of boards was scored when it was manufactured. If you bend along the scores, the boards snap apart easily.

Snap Apart

Prepare To Solder

It’s easiest to solder the IC in place before you mount the headers, so you don’t have to work around the protruding pins.

If this is your first time soldering surface mount ICs, patience and a steady hand are the key to good solder joints.

  • Neatness Counts – you want to put on enough solder to join the legs to the pads, but not so much that adjacent legs are accidentally bridged.
  • Work Quickly – if you leave the hot soldering iron on the board too long, you risk burning the traces and pads off the board. You want the iron at a temperature where the solder flows almost immediately when you apply it to the iron. Somewhat counter-intuitively, a hotter iron can be less damaging than a cooler one – having the iron at a hotter temperature allows you to work more quickly, reducing the potential for damage.

Solder IC In Place

First, heat one corner land (aka pad) on the PCB.

Heating first pad

Once it’s hot, flow a little solder onto it.

One Solder Blob

Pin 1 of the IC is usually marked with a small dimple in the IC body, or that end of the chip is marked with a notch. Line these marks up with the corresponding marks in the silkscreen. The silkscreen actually has three marks, a notch at one end of the IC, a dot within the IC outline, and a dot just outside the IC (which remains visible once the IC is soldered down).

SOIC Pin1 Marks

Grab the IC with the tweezers, and orient it over the footprint. Reheat the solder blob from the previous step, so the IC lead adheres to it. Press the IC down flat before the solder cools.

One Leg Soldered

At this point, it doesn’t have to be a perfect solder fillet, but the IC should be sitting flat on the board, and all of the leads should align with the PCB pads. If the alignment isn’t good, or if pin one is the wrong way around, reheat the solder, and adjust the placement. This becomes a lot harder to fix after more pads get soldered down.

With the chip properly aligned, you can work your way around the chip, soldering each lead. It works best if you use the tip of the soldering iron to heat the IC lead and the PCB land at the same time, then flow a tiny bit of solder to join them.

All Leads Soldered

When you get back to the first lead, you can reheat the joint, flow a little more solder, and make sure the leave a neat fillet.

Solder In Header Pins

With the IC in place, now you can solder on the header pins. It’s easier if you have a jig that can hold the pins while you solder. It turns out that a solderless breadboard has a bunch of holes with the proper alignment!

Start by breaking off the 4-pin segments off the header. Insert them into the breadboard, two rows apart.

Pin in Breadboard

Set the PCB over the headers. Take care to keep the pins aligned straight up and down.

PCB On  Pins

Work you way around the PCB, soldering each pin from the top of the board. When it’s complete, it should look like the board below.

Fully Assembled

Deflux

Once you’ve finished soldering, look at the solder joints. If they appear to have a yellow or brown coating on or around them, the board has flux residue (under a magnifying glass, it might look like burnt sugar). Flux is acidic, and can cause problems with long-term reliability, so it’s best to clean it off.

You’ll have to check the documentation for your solder for the proper cleaning methodology. Some flux is water soluble, while some requires a solvent like isopropyl alcohol or acetone.

Verify

Before we jump into applications of the SOIC-to-DIP adapter board, let’s take a moment to doublecheck our work.

A quick visual inspection can help spot solder bridges, or solder joints that didn’t flow properly. It’s also a good time for one last check, to make certain that pin one of the SOIC is properly oriented.

Whoops!

For a little extra confidence, you can also use a multimeter in continuity mode, to verify that the legs of the SOIC are connected to the pins.

Using The Adapter

Adapter Orientation

The pins of the DIP footprint are rotated 90° in relation to the pins of the SOIC. We covered the pin-1 markings for the SOIC in the assembly section.

Pin 1 of the DIP footprint is marked two ways.

First, the solder pad for pin 1 is square, while the others are round.

DIP Pin 1, top

Second, pins 1 and 8 are marked in the legend silkscreened on the bottom of the board.

DIP Pins, bottom

Case Studies

On a Breadboard

This adapter is useful when you want to build a breadboard prototype using a chip that’s only available in SOIC. It allows the chip to properly fit the rows of the breadboard.

Breadboard Example

Dual-opamp Oscillator On Breadboard

Upgrading Old Devices

Another common use of a SIOC-to-DIP adapter is upgrading or modifying existing equipment.

At one time, this was a way to update the BIOS on a PC motherboard, though more recently DIP-8 EPROMS have been less prevalent, and surface-mount memories are more commonplace, which are usually reprogrammable without being removed from the motherboard.

Chip substitution is also a common practice among hi-fi and pro audio enthusiasts, sometimes called chip rolling or POOGE-ing (Progressive Optimization Of Generic Equipment). Many of these devices are filled with single or dual operational amplifiers in DIP-8 packages. It can be an easy, inexpensive upgrade for an older device to put in newer opamps, which feature lower distortion, less intrinsic noise, and lower DC-offset. Sometimes these newer amplifiers are only available in surface-mount packages, such as the Texas Instruments OPA1641/1642.

Modded PCB

When doing modifications of this sort, there are a couple of things to be aware of.

  • First, note whether the original equipment has the IC in a socket. If so, it should be easy to remove the old chip, and install the adapter.
  • If there is no socket, and the old IC is soldered directly to the board, take care in removing the old IC, to prevent damaging the PCB. It might be easier to cut the legs off the old IC, and desolder them one-by-one.
  • If there wasn’t a socket, you might consider installing one as part of the upgrade.
  • Finally, note the orientation of the IC before you begin, so you can be certain to get the replacement in properly.

Resources and Going Further

Resources

This board is a redesign of the now retired 8-Pin SOIC-DIP adapter.

If you’re debugging SOIC-8 based designs, you might find the SOIC-8 test clip to be useful.

We also offer a number of other surface mount to through-hole conversion boards:

Going Further


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


MPU-9150 Hookup Guide

$
0
0

MPU-9150 Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The MPU-9150 is a nine degrees of freedom (9DOF) inertial measurement unit (IMU) in a sigle package. It houses a 3-axis accelerometer, 3-axis gyroscope, 3-axis magnetometer and a Digital Motion Processor™ (DMP™) hardware accelerator engine. The range of each sensor is configurable: the accelerometer's scale can be set to ±2g, ±4g, ±6g, ±8g, or ±16g, the gyroscope supports ±250, ±500, and ±2000 °/s, and the magnetometer has full-scale range of ±1200µT (±12 gauss).

MPU-9150

The MPU-9150 supports I2C. There is a single reference to in the datasheet for SPI, but all other evidence points to the contrary. We have only testing using I2C, and, for the purposes of this tutorial, we will only be covering how to use this device in I2C mode.

Covered In This Tutorial

This tutorial is devoted to all things MPU-9150. First we'll introduce you to the breakout board. Then we'll switch over to example code and show you how to interface with the board using an Arduino and our [SFE_MPU-9150 Arduino library](https://cdn.sparkfun.com/assets/learn_tutorials/3/9/7/MPU-9150_libraries.zip).

The tutorial is split into the following sections:

Required Materials

This tutorial explains how to use the MPU-9150 Breakout Board with an Arduino. To follow along, you’ll need the following materials:

The MPU-9150 is a 3.3V device! Supplying voltages greater than 6V can permanently damage the IC. InvenSense recommends running from 2.375V to 3.465V. As long as your Arduino has a 3.3V supply output, and you're OK with using I2C, you shouldn't need any extra level shifting.

Suggested Reading

If you’re not familiar with some of the concepts below, we recommend checking out that tutorial before continuing on.

Hardware Overview

The Pinout

In total, the MPU-9150 Breakout breaks out 11 pins.

MPU-9150 product photo

The bare-minimum connections required are broken out on the left side of the board. These are the power and I2C pins (the communication interface the board defaults to):

Pin LabelPin FunctionNotes
GNDGround0V voltage supply
VCCPower SupplySupply voltage to the chip. Should be regulated between 2.375V and 3.465V.
SDAI2C: Serial DataI2C: Serial data (bi-directional)
SCLSerial ClockI2C serial clock (up to 400kHz)

The remaining pins break out additional functionality and interrupt outputs:

Pin LabelPin FunctionNotes
ESDAuxiliary I2C master serial data9150 can act as a master or pass-through to additional I2C devices.
ESCAuxiliary I2C master serial clock9150 can act as a master or pass-through to additional I2C devices.
COUTClock outputOutputs a 50% duty cycle square wave (see register map).
CINClock inputOptional external reference clock input, grounded through jumper.
I using an external clock source, cut 'CLK' jumper.
AD0I2C Slave Address LSBIf low I2C address is 0x68, else 0x69. Connected to jumper. (0x68 default)
FSYNCFrame synchronizationExternal frame sync input that latches to capture external bus interrupts
If using this pin cut 'SYNC' jumper.
INTInterrupt pinConfigurable digital output to signal the host processor of an event.

Power Supply

The VCC and GND pins are where you'll supply a voltage and 0V reference to the IC. The breakout board does not regulate this voltage, so make sure it falls within the allowed supply voltage range of the MPU-9150: 2.375V to 3.465V. Logic voltage levels can be as low as 1.8V ±5% up to VCC.

The communication pins are not 5V tolerant, so they’ll need to be regulated to within a few mV of VDD.

Communication

SDA, SCL, ESD, and ESC are used for the I2C interfaces. The auxiliary clock and data pins will require external pull-up resistors. These ave to be tuned on a case-by-case basis depending on bus capacitance to get proper rise times.

SDA and SCL have integrated 10KΩ pull-ups. If you plan on using more than one I2C device on the bus, you might want to remove these pull-ups. If the I2C lines are pulled-up too strongly by multiple sets of pull-ups, the bus will likely be out of spec and not function correctly.

The following image shows a stock PCBA on the left, and one with the pull-up resistors removed on the right. To remove these, I recommend reflowing a fair amount of solder onto the resistors. It doens't take very long to fully cover all 4 joints with molten solder and the two part will slide right off. So easily in my case that I wasn't able to capture a picture of the excess solder before the parts had come off. Wick off the excess solder, wipe clean with some DI water, and you are done.

Pull-ups removed

Interrupts

There are a variety of interrupts on the MPU-9150. While connecting up to these is not as critical as the communication or power supply pins, using them will help you get the most out of the chip. The INT pin is a digital output to the host controller. The FSYNC pin can be configured as an interrupt input to optionally be passed through out the INT pin.

These can be programmed to interrupt as either active-high or active-low. More details on these configurations can be found in the product register map.

The Jumpers

The most commonly used jumper will be to the address pin (AD0). It defaults to being pulled to ground selecting address 0x68, but with a soldering iron can be changed to be pulled up, switching the I2C address to 0x69.

The AD0 pin broken out is connected directly to ground by default. Alternatively it's connected straight to VCC. Make sure to remove the solder from both sides of the 3-way jumper before connecting it externally.

Address jumper

The address selection jumper on the front of the board. Allows you to select the LSB of the I2C address

The intention of these jumpers is to make it as easy-as-possible to use the board; using as few wires as possible. The CLK jumper is used to ground the external clock input as the datasheet recommends when not using an external clock. Make sure to cut this jumper if you attach an external clock to the CIN connection. The SYNC jumper ties FSYNC to ground as the manufacturer instructs one to do when not using it. Make sure to cut this jumper if use the FSYNC through hole connection.

Back of MPU-9150 Breakout

To disable any of these jumpers, whip out your handy hobby knife, and carefully cut the small traces between middle pad and edge pads.

Funny Business

Be very careful trusting the datasheet. It's full of inconsistencies or lacking clarification. For example pin 22. There is a single reference to it functioning as a clock output (next image). There are several places stating that it's not to be used, such as the table shown two images below.

Clock output, is it real?

Only reference to CLKOUT in datasheet


Clock output, is it real?

One of several examples of pin 22 being recommended to not be connected or a clock

The register map reads "This bit also enables the clock output.", but that's the only reference. It's not even specified clearly to which bit they are referring. We were able to test this, and sure enough it outputs a clock. Maybe this clock is is okay to use. Maybe it was designed for factory testing only.

Clock output

Enabling this clock output was persistent even after a power cycle. Be careful when changing under documented bits in the registers!

SPI is another example of being poorly documented. The following image implies that the address selection line is also SDO. The digital IO power supply pin is also the chip select line. Most serial peripherals we are familiar with don't source power out their chip select pins.

Clock output

Only reference to SPI in the datasheet or the register map

Finally one last quote to show how amazing the datasheet is: "The internal registers and memory of the MPU-9150 can be accessed using either I2C at 400 kHz." Either fast mode I2C, or what? As often as we tell you to RTFM, sometimes the manual can be misleading.

Hardware Assembly

The basic use case for the MPU-9150 requires 4 connections to the µController or µProcessor; power, ground, I2C clock and data. The following images shows how we used a SparkFun FTDI Basic Breakout, and an 3.3V Arduino Pro Mini to power and interface to an MPU-9150. The demo required the use of an interrupt (right-most yellow jumper) connected to D2 (INT0).

MPU-9150 connected to a 3.3V Pro Mini

An MPU-9150 wired up to and Arduino Pro Mini for the MPU6050_DMP6 demo

Make connections to the breakout anyway that makes you happy. The board in the above photo has a right angle header soldered on because that made us happy the day we built it up. We could have used a straight header, or wire, etc. Please note that different mounting orientations will alter the orientation of the axes. Make sure your code matches the physical orientation for your projects.

For this demo, we made the following connections:

Arduino Pro MiniMPU‑9150 BreakoutNotes
VCCVCC+3.3V
GNDGND+0V
SDASDASerial data @ +3.3V CMOS logic
SCLSCLSerial clock @ +3.3V CMOS logic
D2INTINT0 on Arduino | Interrupt output "totem pole or open-drain" on MPU-9150

The whole system in our testing was powered via USB through the FTDI basic.

USB to FTDI to Pro Mini to MPU-9150 Breakout Fritzing diagram

Electrical connections for demo

Installing the Arduino Library

Download and Install the Library

Visit the GitHub repository to download the most recent version of the libraries, or click the link below:

Download the MPU-9150 Arduino Libraries

For help installing the library, check out our Installing an Arduino Library tutorial. You'll need to move/copy the both the I2Cdev and MPU6050 directories inside the firmware directory into the libraries directory within your Arduino sketchbook. If you don't have a directory called libraries, create one and drop both directories in there.

The example Arduino code allows you to do things like print raw accelerometer, gyro, and magnetometer data. The original library came from i2cdevlib.com and was based on the very similar MPU-6050, which only used an accelerometer and gyro. The MPU-6050 device library was modified to include raw magnetometer data for the MPU-9150.

Running the MPU6050_DMP6 Example

Now, you can now run the example sketches. Open File ⇒ Examples ⇒ MPU6050 ⇒ Examples ⇒ MPU6050_DMP6. By default, this sketch is configured to do a fun teapot demo that uses processing. That’s a little more involved than the scope of this hookup guide. We will output the acceleration components with gravity removed.

Uncomment line 102 //#define OUTPUT_READABLE_REALACCEL. Comment out line 112 #define OUTPUT_TEAPOT. Compile and upload the sketch. When it finishes uploading, open the serial monitor, and set the baud rate to 115200 baud. You should see this:

Initializing I2C devices...
Testing device connections...
MPU6050 connection successful

Send any character to begin DMP programming and demo:

At the top of the serial monitor type any ‘normal’ character (such as alphanumeric) and press Send. Your system should respond with:

Initializing DMP...
Enabling DMP...
Enabling interrupt detection (Arduino external interrupt 0)...
DMP ready! Waiting for first interrupt...

If you have the interrupt line connected properly, you should see lines similar to this:

areal   -8680   1460    -1448
areal   -9721   1460    -1463
...

Resources & Going Further

Hopefully that info dump was enough to get you rolling with the MPU-9150. If you need any more information, here are some more resources:

Going Further

Now that you’ve got the MPU-9150 up-and-running, what project are you going to incorporate motion-sensing into? Need a little inspiration? Check out some of these tutorials!

ITG-3200 Hookup Guide

Learn how to interact with the ITG-3200 Triple Axis Gyroscope.

LSM9DS0 Hookup Guide

How to assemble, connect to, and use the LSM9DS0 -- an accelerometer, gyroscope, and magnetometer all-in-one.

VL6180 Hookup Guide

Get started with your VL6180 based sensor or the VL6180 breakout board.

APDS-9960 RGB and Gesture Sensor Hookup Guide

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

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

Si4703 FM Radio Receiver Hookup Guide

$
0
0

Si4703 FM Radio Receiver Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

This breakout board enables you to tune in to FM radio stations, using the Si4703 FM tuner chip from Silicon Laboratories. This IC also works well for filter and carrier detection, and enables data such as the station ID and song name to be displayed to the user.

Si4703

Required Materials

You will need the following materials to work on this project.

Keep in mind you will also need standard soldering materials to complete this tutorial, as well as either a set of speakers or headphones with a 3.5mm jack to plug into the Si4703 board.

Suggested Reading

If you aren’t familiar with any of the concepts below, check out these links and get caught up before moving ahead with the Si4703.

Hardware Overview

The Si4703 Breakout Board breaks out multiple pins from the IC. For the power bus, the 3.3V and GND pins are broken out. Keep in mind that while the IC is tolerant up to 5V, the communication pins are only 3.3V tolerant, and therefore should only be used in 3.3V systems. If you need to use this in a 5V system, check out our tutorial on using logic level converters.

alt text

Underside of breakout board showing pin labels

For communication, the breakout board provides access to SDIO and SCLK for I2C communication. The RST pin is also broken out for ease of resetting the module.

SEN is also broken out, and enables the user to change the mode of functionality of the IC. SEN is pulled high on the breakout board to enable I2C communication as mentioned previously. However, by changing the state of SEN along with SDIO, you can change the mode of functionality between a 3-wire interface and 2-wire interface.

Finally, the last two pins broken out are the GPIO1 and GPIO2 pins. These can be used as general input/output pins, but also can be used for things like the RDS ready, seeking or tuning functions.

The board does not have a built-in antenna on it. However, by using headphones or a 3 foot-long 3.5mm audio cable, the wires will function as an antenna and will therefore negate the need for an external antenna on the board. If you are not planning on using either of these, you will need to modify the board to add in an antenna.

Hooking Up to an Arduino

First, you will need to prepare both the Si4703 board and the Arduino Pro Mini. Solder on the male headers to both boards. You will need headers on both the FTDI header, as well as the pins that you will be connecting to the Si4703.

Pin Connections

Once you have headers soldered, you will need to use the jumper wires to connect between the Si4703 and the Pro Min. Remember, we are using a 3.3V Pro Mini to prevent damage to the logic on the Si4703.

Si4703 → 3.3V Pro Mini

  • GND → GND
  • 3.3V → VCC
  • SDIO → A4
  • SCLK → A5
  • RST → D2

You will then also need to hook up the Pro Mini to the FTDI board, and connect to your computer over USB.

Installing the Library

Now that the hardware is hooked up and connected, it’s time to prepare to upload code. First you need to install the Arduino library into the IDE. If you are unaware how to do this, please check out our tutorial here. You can download the code here.

Once the library is properly installed, please open up the example sketch labeled “Si4703_Radio_Test”. Make sure you select the “Arduino Pro or Pro Mini (3.3V, 8MHz) w/ ATMega328” under the “Tools -> Boards” heading. Select the proper COM port for your FTDI device under “Tools -> Serial Port”. Upload the sketch to the board.

Once you have it uploaded, open up your Serial terminal (either through the Arduino IDE or your favorite terminal program). Open the connection with the settings 9600bps, 8, N, 1, and you should see the following displayed on the terminal.

Terminal prompt

You can then choose from any of the options listed. If you initially send the board option “a”, you should see the following displayed back.

Favorite Station

These favorite stations are pre-determined in the sketch, so feel free to change those to your own favorite stations if you would like.

else if (ch == 'a')
{
  channel = 930; // Rock FM
  radio.setChannel(channel);
  displayInfo();
}
else if (ch == 'b')
{
  channel = 974; // BBC R4
  radio.setChannel(channel);
  displayInfo();
}

Keep in mind you will need to upload the code to the board again to update to the new stations. You can then direct the tuning either up or down, and control the volume of the board. For example, to tune to station 95.7 FM here in Boulder, I sent the commands: u, u, +, +, +, +, +, +, +, +, +, +, +, +, +, u, u, u, u, u, u. This results in the following in the serial terminal.

Tuned Radio Station

For this example, I am using my headphone wire as the anntena. Because of this, I was not necessarily able to receive stations that I often can when I’m not using a headphone wire as an antenna while connected to my computer (EMI is so much fun!). Play around with moving around or using different headphone wires and see how radio reception can change.

Resources and Going Further

Going Further

Now that you have your FM Tuner up and tuned to your favorite stations, you can start tweaking your circuit. You could add in a sensor to tune your board for you, or have it set up on a timer with a clock. If you come up with a really cool project or mod, let us know! We’d love to hear about it.

Additional Resources

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

Check out these additional resources for more information and other project ideas.


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

LSM6DS3 Breakout Hookup Guide

$
0
0

LSM6DS3 Breakout Hookup Guide a learn.sparkfun.com tutorial

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

Introduction

The LSM6DS3 is a accelerometer and gyroscope sensor with a giant 8 kbyte buffer and embedded processing interrupt functions, specifically targed at the cellphone market. The sensor is super-flexible and can be configured specifically for an application. We’ve put together a driver and slew of examples to help you explore the possibilities.

alt text

The LSM6DS3 Breakout Board.

Some of the things the LSM6DS3 can do:

  • Read accelerometer data up to 6.7 kilosamples per second, for super accurate movement sensing
  • Read gyroscope data up to 1.7 kilosamples per second
  • Operates from 1.25mA for up to 1.7 ksps modes
  • Read temperature
  • Buffer up to 8 kbytes of data between reads (built-in FIFO)
  • Count steps (Pedometer)
  • Detect shocks, tilt, motion, taps, double-taps
  • Host other sensors into its FIFO
  • Drive interrupt pins by embedded functions or by FIFO low-capacity/overflow warning.

Covered In This Tutorial

This tutorial gives you all you need to get going with the LSM6DS3. We’ll introduce you to the chip itself, then the breakout board. Then we’ll switch over to example code and show you how to interface with the board using an Arduino and our SparkFun LSM6DS3 Arduino library.

The tutorial is split into the following pages:

Required Materials

Get the datasheet and application notes now. Open them in a non-browser viewer that can display the index/table of contents in a pane. There is so much information, paned viewing is a must!

This tutorial explains how to use the LSM6DS3 Breakout Board with an Arduino. To follow along, you’ll need the following materials:

The LSM6DS3 is a 3.3V device! Supplying voltages greater than ~3.6V can permanently damage the IC. As long as your Arduino has a 3.3V supply output, and you're OK with using I2C, you shouldn't need any extra level shifting. But if you want to use SPI, you may need a level shifter.

A logic level shifter is required for any 5V-operating Arduino (UNO, RedBoard, Leonardo, etc). If you use a 3.3V-based ‘duino – like the Arduino Pro 3.3V or 3.3V Pro Mini– there is no need for level shifting.

Suggested Reading

If you’re not familiar with some of the concepts below, we recommend checking out that tutorial before continuing on.

Hardware Overview

The Pinout

In total, the LSM9DS0 Breakout breaks out 11 pins.

alt text

Top side. The jumper is solderable to easily change options.

The bare-minimum connections required are broken out on the left side of the board. These are the power and I2C pins (the communication interface the board defaults to). These pins can be used for the SPI interface as well:

Pin LabelPin FunctionNotes
GNDGround0V voltage supply. Spare GND pin to connect more stuff!
VDDPower SupplySupply voltage to the chip. Should be regulated between 1.8V and 3.6V. Spare VDD provided for general use as well.
SDA/SDII2C: Serial Data
SPI: MOSI
I2C: Serial data (bi-directional)
SPI: Device data in (MOSI)
SCLSerial ClockI2C and SPI serial clock.
SDO/SA0I2C: Address
SPI: MISO
I2C: Address LSB
SPI: Device data out (MISO)
CSI2C: Mode
SPI: CS
I2C: Select I2C (disconnected)
SPI: Chip select (Slave select)

The remaining pins are broken out on the other side. These pins break out SPI functionality and interrupt outputs:

Pin LabelPin FunctionNotes
INT2Accel/Gyro Interrupt 2INT1 and INT2 are programmable interrupts for the accelerometer and gyroscope. They can be set to alert on over/under thresholds, data ready, or FIFO overruns. Make sure these are connected to an INPUT pin to prevent driving 5v back into the LSM6DS3.
INT1Accel/Gyro Interrupt 1
OCSAux SPI 3-wireThese pins are used to attach slave I2C and 3-wire devices for FIFO data collection. This function is not covered in this tutorial.
SCXAux Clock
SDXAux Data

alt text

Bottom side. For most use cases, these jumpers will stay as is.

Power Supply

The VDD and GND pins are where you’ll supply a voltage and 0V reference to the IC. The breakout board does not regulate this voltage, so make sure it falls within the allowed supply voltage range of the LSM9DS0: 1.8V to 3.6V. Below is the electrical characteristics table from the datasheet.

alt text

The communication pins are not 5V tolerant, so they’ll need to be regulated to within a few mV of VDD.

Interrupts

There are a variety of interrupts on the LSM6DS3. While connecting these is not as critical as the communication or power supply pins, using them will help you get the most out of the chip.

The interrupts are INT1 and INT2. These can both be programmed to respond to the following conditions:

INT1 by INT1_CTRL register

  • Step detected
  • Significant motion (shock, drop)
  • FIFO full
  • FIFO overrun
  • FIFO threshold reached (Datasheet calls this the “watermark”
  • Boot status
  • Gyroscope data ready
  • Accelerometer data ready

INT1 by MD1_CFG

  • Inactivity
  • Single tap
  • Wake-up
  • Free-fall
  • Double tap
  • 6D (orientation)
  • Tilt
  • Timer

INT2 by INT2_CTRL register

  • Step detected after delta time
  • Step counter overflowed
  • FIFO full
  • FIFO overrun
  • FIFO threshold reached
  • Temperature data ready
  • Gyroscope data ready
  • Accelerometer data ready

INT2 by MD2_CFG

  • inactivity
  • Single-tap
  • Double-tap
  • Wake-up
  • Free-fall
  • Double tap
  • 6D
  • Tilt
  • Ironing interrupt

Only a few interrupt examples are provided. See the datasheet and application guide for using the advanced interrupt features.

The Jumpers

Jumper LabelJumper Function
ADDRUse to sellect address 0x6A or 0x6B(default) for I2C communication. This jumper must be opened for SPI mode, or the MISO line will not supply data
PU_ENThis trace-connected jumper enables 4.7k resistors on SDA and SCL for I2C. SPI works with these connected, but really they should be cut apart for better signal shape at high speeds and to lower power consumption
SCX and SDXST recommends pulling the unused SCX and SDX to power or ground when not in use. If connecting slave devices, cut these traces.

The ADDR jumper is commonly reconfigured for I2C addresses and SPI mode, so it is solder jumpered.

The other jumpers are probably not for most users, but if it is necessary, whip out your handy hobby knife, and carefully cut the small traces between pads. Even if you’re using SPI, though, the jumpers shouldn’t hinder your ability to communicate with the chip.

Assembly

The easist way to connect the LSM6DS3 to an arduino compatible board is to use the I2C interface. The breadboard is shown for reference, but the wires can be soldered directly to the LSM6DS3 breakout and plugged into the arduino.

alt text

Here’s how to connect the SPI lines to a 5V system using a SparkFun Logic Level Converter. Be sure to orient the converter’s low side to the LSM6DS3. If using a teensy or other 3.3V microcontroller, the SPI lines can be connected directly.

alt text

Use the 4 mounting holes to get the LSM6DS3 firmly attached to the thing that is being measured! Here, a 1x4 is used as a test platform to filter movement noise. Also shown here is a connection to the INT1 pin (Pin D3 on UNO and RedBoard). The other ends of the wires plug directly into the RedBoard.

alt text

Installing the Arduino Library

We’ve written an Arduino library to help make interfacing with the LSM6DS3’s gyro, accelerometer, and temperature sensor as easy-as-possible. Visit the GitHub repository to download the most recent version of the library, or click the link below:

Download the SparkFun LSM6DS3 Arduino Library

For help installing the library, check out our How To Install An Arduino Library tutorial. You’ll need to move the SparkFun_LSM6DS3_Arduino_Library folder into a libraries folder within your Arduino sketchbook.

Alternatively, if you are running a relatively current version of the Arduino IDE (1.6.2 or newer) you will find the library in the library manager if you search for “LSM6DS3”. For more details see the official Arduino library manager documentation.

Using the Arduino Library

Test the library

  • MinimalistExample - The easiest configuration

Hook up the LSM6DS3 to the I2C bus, and click “File -> Examples -> Sparkfun LSM6DS3 Breakout -> MinimalistExample”. This example demonstrates the highest level of usage. The default settings in the driver are I2C at the default address, 0x6B, so all you have to do is create a variable of the type “LSM6DS3” and .begin(); it.

Key parts:

language:c
LSM6DS3 myIMU; //Default constructor is I2C, addr 0x6B

This line creates a variable myIMU of type LSM6DS3. As the comment says, the default parameters are what we desire.

language:c
//Call .begin() to configure the IMU
myIMU.begin();

Calling .begin(); causes the driver to initialize the IMU. .begin can pass some diagnostics information back, but it’s not necessary for this basic example.

language:c
  Serial.println(myIMU.readFloatAccelX(), 4);

Calling .readFloatAccelX() causes the driver to go get data from the IMU. In this line, the data is also passed to the print function.

Configure More Settings

  • FifoExample - Demonstrates using the built-in buffer to burst-collect data - Good demonstration of settings

To get the most out of the LSM6DS3 you’ll probably want to configure it. This sketch was put together as a template that shows you ALL the settings that the driver supports, and you can remove lines you don’t need.

The creation of myIMU has a dark secret. If you’re not using I2C, address 0x6B (defualt), you can specify your port during the construction. From the example,

language:c
LSM6DS3 myIMU( SPI_MODE, 10 );

…we specify SPI_MODE, a custom keyword, and pin 10. This makes use of the SPI interface and uses pin 10 for the CS line. As the logic is not arduino specific, any pin can be CS.

Here’s the low-down on the arguments that can be used.

language:c
LSM6DS3 <your variable name>( SPI_MODE, <CS PIN NUMBER> );

…or…

language:c
LSM6DS3 <your variable name>( I2C_MODE, <address> );

…where address can be 0x6A or 0x6B.

Note: This example pulls a lot of data from the IMU. SPI is used for better performance.

The other settings:

language:c
//Over-ride default settings if desired
myIMU.settings.gyroEnabled = 1;  //Can be 0 or 1
myIMU.settings.gyroRange = 2000;   //Max deg/s.  Can be: 125, 245, 500, 1000, 2000
myIMU.settings.gyroSampleRate = 833;   //Hz.  Can be: 13, 26, 52, 104, 208, 416, 833, 1666
myIMU.settings.gyroBandWidth = 200;  //Hz.  Can be: 50, 100, 200, 400;
myIMU.settings.gyroFifoEnabled = 1;  //Set to include gyro in FIFO
myIMU.settings.gyroFifoDecimation = 1;  //set 1 for on /1

myIMU.settings.accelEnabled = 1;
myIMU.settings.accelRange = 16;      //Max G force readable.  Can be: 2, 4, 8, 16
myIMU.settings.accelSampleRate = 833;  //Hz.  Can be: 13, 26, 52, 104, 208, 416, 833, 1666, 3332, 6664, 13330
myIMU.settings.accelBandWidth = 200;  //Hz.  Can be: 50, 100, 200, 400;
myIMU.settings.accelFifoEnabled = 1;  //Set to include accelerometer in the FIFO
myIMU.settings.accelFifoDecimation = 1;  //set 1 for on /1
myIMU.settings.tempEnabled = 1;

//Non-basic mode settings
myIMU.settings.commMode = 1;

//FIFO control settings
myIMU.settings.fifoThreshold = 100;  //Can be 0 to 4096 (16 bit bytes)
myIMU.settings.fifoSampleRate = 50;  //Hz.  Can be: 10, 25, 50, 100, 200, 400, 800, 1600, 3300, 6600
myIMU.settings.fifoModeWord = 6;  //FIFO mode.
//FIFO mode.  Can be:
//  0 (Bypass mode, FIFO off)
//  1 (Stop when full)
//  3 (Continuous during trigger)
//  4 (Bypass until trigger)
//  6 (Continous mode)

Read the datasheet, and select the parameters that suit your needs. They can only take on the values listed, or the default value will be used. If you don’t care about a setting, omit that line.

A Low-Level Example

  • LowLevelExample - Demonstrates using only the core driver without math and settings overhead

This little example was put together to show you how to use the sensor without all the crazy floating point math. It saves memory in the processor (roughly half), but you won’t have access to all the fancy math functions.

language:c
myIMU.writeRegister(LSM6DS3_ACC_GYRO_CTRL1_XL, dataToWrite)

and

language:c
myIMU.readRegister(&dataToWrite, LSM6DS3_ACC_GYRO_CTRL4_C);

show reading and writing to arbitrary registers

The Other Examples

  • InterruptFreeFall - Embedded function demonstrating free-fall detection
  • InterruptHWTapConfig - Embedded function demonstrating tap and double-tap detection
  • MemoryPagingExample - Demonstrates switching between memory pages
  • MultiI2C - Using two LSM6DS3s over I2C
  • MultiSPI - Using two LSM6DS3s over SPI
  • Pedometer - Embedded function demonstrating step-counting feature

User API Functions

Here’s an explanation of the regular functions the user might call

Construction:

language:c
LSM6DS3( uint8_t busType, uint8_t inputArg );

busType can be SPI_MODE or I2C_MODE.

For SPI_MODE, inputArg specifies pin number for I2C_MODE, inputArg specifies either address 0x6A or 0x6B

language:c
status_t begin(void);

always call .begin(); before using the following functions!

language:c
int16_t readRawAccelX( void );
int16_t readRawAccelY( void );
int16_t readRawAccelZ( void );
int16_t readRawGyroX( void );
int16_t readRawGyroY( void );
int16_t readRawGyroZ( void );

These functions return the 16bit raw values from the LSM6DS3.

language:c
float readFloatAccelX( void );
float readFloatAccelY( void );
float readFloatAccelZ( void );
float readFloatGyroX( void );
float readFloatGyroY( void );
float readFloatGyroZ( void );

These functions return the floating point real-world values. Accel functions return in g’s and Gyro return in degrees/second.

language:c
int16_t readRawTemp( void );

Gets the raw temperature value

language:c
float readTempC( void );
float readTempF( void );

Gets the temperature in your favorite scale (sorry, no kelvin)

These next functions operate the FIFO. Using the FIFO is more advanced and definitely requires consulting the datasheet for the LSM6DS3

language:c
void fifoBegin( void );

Configures the FIFO. This will make the FIFO start listening to Accelerometer data and/or gyroscope data, depending on the settings (the settings.accelFifoEnabled = 1; will include the accel in the fifo).

language:c
void fifoClear( void );

This clears the FIFO by reading out all the data and dumping it. If the FIFO is full and the bus is slow, this may take some time.

language:c
int16_t fifoRead( void );

Get the 16 bits of the next data coming out. This might be accelerometer data or gyroscope data, you can use the status bits to determine which (or by clearing out the FIFO completely and starting from a known reference).

language:c
uint16_t fifoGetStatus( void );

Get the 16 bits of the status word.

language:c
void fifoEnd( void );

Disables the FIFO.

Functions ‘under the hood’

language:c
float calcGyro( int16_t );
float calcAccel( int16_t );

This converts raw values into real numbers. Internally, it uses the .settings to do the math. When using the high-level functions that return floating point numbers, these are internally called.

The only reason they are available to the user is because they can be used to convert the raw data coming out of the FIFO into real numbers. Though, if faster processing is needed (taking short-cuts or staying in raw integer math) they don’t have to be used.

Theory and Example Data

From the nature of the examples, the LSM6DS3 can be used very simply (detect ‘down’, for example) to something much more complicated, like discerning arbitrary motion through space. We hope that after playing around with the examples, you’ll take the library apart and do something truely amazing with it. This section gives you more information about what’s going inside.

The Data

Sure, it’s easy to read single points of data but if you really want good motion detection, you’ll have to pull time-synchronized data and do math at it. The first step is to see what that data would look like, and practice algoritihms to see if your math is any good before you try to debug things in arduino.

Lets take a look at some actual data. Ideally we would use a robot to perfectly articulation the IMU through some test motion, but instead we used an engineer’s arm. For the following tests, the IMU was held stationary, then moved down about 1 foot in about a half-second, then held stationary again. What follows is a select set of graphs.

alt text

alt text

alt text

alt text

These graphs show the same motion with several different settings. Notice that the raw data that is collected at these low-frequency sampling rates consists of steps. The higher the datarate, the finer the steps. Also notice that during what was felt as a smooth downward motion, sometimes non-monotonic slopes are seen, that is, the change in amplitude between steps doesn’t always have the same sign.

Also shown in the graphs is a second trace – but don’t get too excited. This trace is a software filter created by implementing a rolling average of the last 20 samples. This was done with a teensy 3.1, and wasn’t attempted with 328 based microcontroller.

Once the data is collected and filtered, then more advanced threshold and slope detectors can be implemented to get custom motion responses. This is similar to what the ‘embedded functions’ of the LSM6DS3 are actually doing to provide easy-to-use interrupt output.

Resources and Going Further

There are a gazillion ways to use an IMU, from simple gravity sensing to advanced motion tracking. There are so many ways to configure the LSM6DS3! After you’ve used your arduino and the examples to get the hang of things, use this process:

  1. Read the datasheet and application note!
  2. Design an experiment to try an idea
  3. Measure the results

Only this, is the way to improve.

Resources

  • LSM6DS3 Product GitHub Repository– Your revision-controled source for all things LSM6DS3. Here you’ll find our most up-to-date hardware layouts and code.
  • LSM6DS3 Datasheet– This datasheet covers everything from the hardware and pinout of the IC, to the register mapping of the gyroscope and accelerometer.
  • LSM6DS3 Application Note– This application note has the same information as the datasheet, but puts real english words in there to try and help out the humans. Use both this and the datasheet togheter in a tabbed PDF viewer, with the index window open, for maximum efficiency.

Going Further

Need a little inspiration? Check out some of these tutorials!

Dungeons and Dragons Dice Gauntlet

A playful, geeky tutorial for a leather bracer that uses a LilyPad Arduino, LilyPad accelerometer, and seven segment display to roll virtual 4, 6, 8, 10, 12, 20, and 100 side dice for gaming.

Tilt-a-Whirl Hookup Guide

A simple hook up guide to get started with the Tilt-a-Whirl sensor.

Wake-on-Shake Hookup Guide

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

LSM6DS3 Breakout Hookup Guide

A hookup guide for the LSM6DS3, which features a 3-axis accelerometer, 3-axis gyroscope, and FIFO buffer.

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

Planning a Wearable Electronics Project

$
0
0

Planning a Wearable Electronics Project a learn.sparkfun.com tutorial

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

Introduction

Wearable electronics can be one of the most fascinating yet frustrating activities for beginners. In addition to circuit design and coding, we also have to take into consideration the construction time involved in sewing, and the pros and cons of different fabrics or materials to which the circuits may be attached. Here’s a guide to planning a successful project with LilyPad or other wearables products.

alt text

Suggested Reading

Brainstorming

Let’s begin with a rough outline of what our project looks like and what it does. Use a method that works for you, such as:

  • Creating an inspiration board or collage
  • Drawing rough sketches in a notebook
  • Writing a list of features or ideas for project function or design
  • Doing online research and collecting inspirational projects
  • Making wish lists of hardware you want to use
  • Thrift shopping or looking through your closet for items to build upon
Knowing Your Limits

It's very easy to dream up a fantastically complex project beyond your personal capabilities, especially when starting out with a new technology. Planning and sketching out your ideas will help give a sense of scale and time needed to complete your project. If you are brand new to wearables, why not try adapting an existing project from one of our tutorials, or starting with a smaller project that may take a few hours versus a few weeks to complete?

Additional Brainstorming Tips:

  • Keep a list of the components you may want to use as well as raw materials, such as fabric or specialty items, along with any of your brainstorming sketches.
  • If starting with an existing garment/fabric project: take photos, make rough sketches of it, or trace key details onto paper to help plan circuit layout.
  • If designing a garment from scratch: make deliberate decisions during your patterning process that include where components may attach or wiring (conductive thread) may run.
  • Identify any problem areas before construction time - are there places on the project that may be difficult to sew onto or to access?

alt text

This student used printed LilyPad images to plan exact placement of a patch that would later be sewn behind the logo of a t shirt.

Project Planning Checklist

Here is a checklist of questions to consider when planning the specifics of your project:

What is the base material/fabric?

Is it delicate, stretchy, thin? You may need reinforcing material such as interfacing so components don’t pull loose or move on the fabric.

How durable does the project need to be?

Is it a one-time showpiece or will it get a lot of use (such as a theater project that needs to survive multiple performances)? Sometimes soldering together components may be a more durable option than sewing. Silicone wire is a great option if you decide to solder components together. Ribbon cable may also be a good option for projects with multiple thread lines such as the three to four connections needed for the LilyPad Pixel boards.

Reinforcing or covering components that are in areas of high flex or wear is also something to consider for the longevity of your project.

Do I want to see the circuit or not?

Hiding components under layers or linings will keep the “magical” quality of the circuit whereas building on top of a costume can incorporate the boards as decorative elements. Experiment with decorative accents such as beads, sequins, or buttons to strategically hide components and make them blend in. If using decorative items with a metallic finish, coat in clear nail polish to avoid accidental shorts in the the thread or components.

Will it be easy to access any switches, batteries, or sensors?

Consider how the inputs will be used - where is the most sensible place for a wearer to access these components? For example, hiding a switch in the back of a dress would make it inaccessible for the wearer to use (unless they are super flexible). A better spot may be along the waistline or sleeves.

Some wearable technologies, like EL Wire, need larger packs for inverters and batteries that may not fit easily in some clothing designs. Others, such as Polymer Lithium Ion Batteries, may be delicate and need a special pouch or placement away from sharp objects or potential crushing. For more information on powering your project, see our tutorial.

How will the circuit be insulated?

Most costuming or wearable projects will be moving on the body and can be prone to short circuits. For conductive thread traces in close proximity to each other, we recommend insulating the project to protect against accidental short circuits. Check out our Insulation Techniques for e-Textiles tutorial for some ideas. This should be the last step in your project once it is tested (on a flat, non-metallic surface) and before it is worn.

Prototyping

After gathering the materials and components planned during brainstorming, it is time to prototype the circuit. To avoid the frustration of sewing things together only to find out they don’t work the way you planned, we recommend using alligator clips to temporarily connect LilyPad components and then testing the circuit and/or code.

If using a product that comes in Protosnap form, such as the ProtoSnap LilyTwinkle, ProtoSnap LilyPad Development Board Simple, or ProtoSnap LilyPad Development Board, you can skip the alligator clips since the boards have traces connecting them. If adding additional sensors or pieces to a Protosnap board, use alligator clips.

alt text

An example of prototyping with alligator clips from our LilyTiny Plush Monster Tutorial.

If you are using a microcontroller, now is the time to start writing some code (or adapting some example code). A basic framework for your project’s behavior or interaction completed before build time will help with any troubleshooting later in the process. Keep in mind that you can always go back and refine or edit your code once the project is completely sewn together as long as you leave the connection point (FTDI headers if using a LilyPad Arduino) easily accessible in your design.

Refining Your Design

After some basic prototyping with your components, take some time to do a more refined sketch or diagram of the circuit layout. This is an opportunity to catch any problems with the design (crossed conductive thread paths, lack of room for components, etc.) before you start the construction process. This final sketch can also serve as a guideline if components get misplaced or moved during the build process.

alt text

An example of a design layout created in a graphics program - note the inclusion of a diagram of the garment as well as detailed labeling of the hook ups for the boards.

alt text

This project uses a handout created by Creativity Labs to finalize the circuit layout.

Diagramming with Fritzing

Fritzing is a great open source tool that allows you to design a schematic and wiring diagrams. The program allows you to drag and drop components in a window and drag wiring lines between them to brainstorm or document hook ups. If you prefer a computer generated circuit diagram to hand sketching, Fritzing is a great choice that also comes pre-loaded with a lot of LilyPad components to use.

D&D gauntlet circuit

An example of a LilyPad Arduino project diagram created with Fritzing.

After doing a final sketch it is time to connect the electronics. Depending on your design, you may also be able to place the clipped pieces on your project to help plan final placement.

Make sure to unplug any power source or battery while moving the pieces to avoid short circuits caused by accidental disconnection of alligator clips or components touching each other during movement.

Build Time

Now that we have all that pesky planning out of the way, it’s time to build a project!

Tips for construction:

  • Break the work down into sections or stages of construction, such as sewing in a LilyPad Arduino first and working on LEDs or sensors in batches.
  • If possible, prototype and test connections as you complete them. This will catch any problems before the project is finished and may allow more time to fix or change as you go.
  • Never work on a powered project! Remember that conductive thread is essentially uninsulated wire. If you were testing a section of the project, be sure to unplug or turn off before beginning construction again.

Resources and Going Further

Hardware Hookup Guides and Wearable Technology Resources:

Project Ideas:


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

Making Music with the FreeSoC2

$
0
0

Making Music with the FreeSoC2 a learn.sparkfun.com tutorial

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

Introduction

The FreeSoC2 is an excellent platform for playing with the capabilities of Cypress PSoC devices. I had never touched a PSoC before this project, so I wasn’t sure exactly what I was getting into. Turns out, they’re a pleasure to work with. Whenever I get a chance to play with a new technology, I like to build a simple musical instrument. Why? Because even the most basic keyboard synthesizer incorporates important concepts like pushbutton input and output, signal generation, signal switching and timing. Building this keyboard gave me a pretty good window into the FreeSoC2 and helped me get a hang of using the PSoC Creator software.

FreeSoC Keyboard

Materials Required

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

Suggested Reading

Before you embark on this build, it’s a good idea to check out this FreeSoC2 Introduction so you have some familiarity with the hardware. Here some other tutorials you may find handy:

Hardware Overview

Before I show you what’s going on in PSoC Creator, let’s take a look at what I have hooked up to the FreeSoC2 board:

PSoC Schematic

The diagram above lays out the connections so that you can trace them visually, but here’s how it breaks down:

  • Pins 5.0 - 5.7 are connected through eight pushbuttons to ground.
  • Pins 3.6 and 3.7 are connected to the wipers of two potentiometers.
  • Pin 4.1 is connected to the input of the Mono Amp Breakout board.
  • A speaker is connected to the output side of the Mono Amp Breakout board.
  • The Mono Amp Breakout and FreeSoC2 board are powered using separate power adapters in order to avoid introducing noise to the amp.

PSoC Schematic

Now that the FreeSoC board is wired up, let’s open up the PSoC Creator software and take a look at the project. You can get the project files from the GitHub Repo here. When you open up the schematic view, you’ll see the whole project at once:

TopDesign

As you can see, it’s split up into a few discrete modules with inputs on the left and outputs on the right. The easiest way to understand what’s happening here is to break it down by section:

Digital Inputs

Stat_Reg

You’ll remember from the hardware overview that we connected 8 pushbuttons to a row of analog pins on the FreeSoC board. In order to read the status of these buttons, we need to route them internally to something called a status register. The status register accumulates the status of up to 8 digital pins and allows you to fetch them using simple function calls in the firmware. Every time we call Status_Reg.Read() it will return an 8-bit number that represents whether each pin is high or low.

Analog Inputs

ADC

To read the potentiometers, we’ll need to set up an ADC. If you’re familiar with the ADC on the Arduino, the SAR on the FreeSoC is very similar. There aren’t enough separate ADCs to set up one for each analog input, which would be a waste of resources anyway, so we need to multiplex the input. The component labeled Pot_Vals is a 2-channel analog multiplexer that allows us to connect either of the two potentiometers to the ADC. To get a reading from a specific potentiometer, the first thing we need to do is call Pot_Vals_Select() to connect the right pin to the ADC. Then we start the ADC conversion and finally retrieve the ADC result.

Signal Generator and Output

WaveDAC

This is the heart of the project, and it’s based on an awesome component called the WaveDAC. The WaveDAC combines a waveform generator with a digital-to-analog converter so that all you need to do in order to make an analog waveform is define the waveshape and the frequency. Each WaveDAC can store two predefined waveshapes that can be selected during runtime by switching the digital input labeled ws.

Because each WaveDAC will only store two waveforms, we need to stack a few of them to get 8 distinct tones. Also, because they’re constantly generating a tone we need a way of switching between the WaveDACs so the outputs are piped into a multiplexer.

Finally, the WaveDAC ws lines are all tied to a control register. A control register is similar the status register except that it works as an output instead of an input. By making simple function calls in the firmware, we can control a number of digital signals during runtime.

Gain and Tremolo

AMP

The last two stages before the final output are the tremolo, which is simply a multiplexer with one input left floating, and the variable gain, which is achieved using a programmable gain amplifier.

You’ll notice that the output from the signal generator stage doesn’t go directly into the Tremolo multiplexer. This is because PSoC Creator doesn’t allow you to connect the output of one multiplexer to the input of another. We got around this by bridging two analog pins together and sending the signal through.

The tremolo effect is achieved by switching the multiplexer back and forth between two channels, one is connected to the output of the signal generator stage and one is left unconnected. By controlling the delay between channels, we can control the rate of the tremolo.

The gain control is achieved by sending the output from the tremolo stage into a Programmable Gain Amplifier or PGA. The PGA amplifies the incoming signal by a factor set during runtime by the firmware.

To find out how all of this works together, we’ll need to tuck into the firmware…

Firmware

Now that the hardware is all hooked up and the PSoC device is configured, it’s time to look over the firmware. The code isn’t very complex but we’ll cut it into sections so that we can break it down by function, starting with the initializing code:

language:c
#include <project.h>
#include <stdbool.h>

int main()
{
/* initialization/startup */

A_B_Start();
C_D_Start();
E_F_Start();
G_A_Start();
OutMux_Start();
Pot_Vals_Start();
ADC_Start();
Tremolo_Start();
Amp_Start();

uint8 InputReg;
int16 Pot_A_val;
int16 Pot_B_val;

Amp_SetGain(Amp_GAIN_01);

The initialization portion of the code is fairly straight-forward. The first few lines are procedure calls to start each of the components from the schematic. Then we set up a few variables to keep track of our status register and potentiometer values. And finally, we need to initialize the programmable gain amplifier.

language:c
for(;;)
{
    Pot_Vals_Select(0);
    CyDelay(25);
    ADC_StartConvert();
    ADC_IsEndConversion(ADC_WAIT_FOR_RESULT);
    Pot_A_val = ADC_GetResult16();

    Pot_Vals_Select(1);
    CyDelay(25);
    ADC_StartConvert();
    ADC_IsEndConversion(ADC_WAIT_FOR_RESULT);
    Pot_B_val = ADC_GetResult16();


    InputReg = Status_Reg_Read();

Here we’ve started the main code loop by reading all of our inputs. For each of our potentiometers, we first select the correct channel on the ADC multiplexer. Then we need to start the conversion which is quick but not instantaneous so before we retrieve the results we need to wait for the conversion to end. The procedure call ADC_IsEndConversion(ADC_WAIT_FOR_RESULT) essentially busy-waits until the ADC conversion is complete and the results are ready to retrieve.

The digital inputs are easier to handle, all we need to do is call Status_Reg_Read() which returns an 8-bit number where each bit represents the status of one input.

language:c
switch(InputReg){

 case 1:
    Control_Reg_Write(0); //0000
    OutMux_Select(0);
 break;

 case 2:
    Control_Reg_Write(1); //0001
    OutMux_Select(0);
 break;

 case 4:
    Control_Reg_Write(1); //0001
    OutMux_Select(1);
 break;

 case 8:
    Control_Reg_Write(2); //0010
    OutMux_Select(1);
 break;

 case 16:
Control_Reg_Write(2); //0010
OutMux_Select(2);
 break;

 case 32:
Control_Reg_Write(4); //0100
OutMux_Select(2);
 break;

 case 64:
Control_Reg_Write(4); //0100
OutMux_Select(3);
 break;

 case 128:
Control_Reg_Write(8); //1000
OutMux_Select(3);
 break;

 default:
    OutMux_DisconnectAll();
 break;

}

This switch/case statement selects the correct output channel and waveshape depending on the key that’s being pressed. Two function calls are required to play a tone: first we need to write to the control register in order to select the proper waveshape on the proper WaveDAC and secondly, we need to select the proper output channel on the multiplexer. The default case is OutMux_DisconnectAll() which shuts off the sound when no key is being pressed.

language:c
Pot_A_val = Pot_A_val*20/1024;
Pot_B_val = Pot_B_val*3/1024;

if(Pot_A_val > 1){

    CyDelay(Pot_A_val*5);
    Tremolo_Select(1);
    CyDelay(Pot_A_val*5);
    Tremolo_Select(0);

}else{

    Tremolo_Select(0);

}

The above section determines the rate of the tremolo. Firstly, we re-map the potentiometer values that we retrieved earlier to a smaller and more useful range. Then we check to see if the potentiometer reading is above a certain value because if the tremolo rate is 0, we want to be sure that it isn’t stopped on the dead channel. If the potentiometer value is above 1, we cycle the tremolo on and off once using delays in between determined by the potentiometer value.

language:c
switch(Pot_B_val){

 case 0:
    Amp_SetGain(Amp_GAIN_01);
    break;

 case 1:
    Amp_SetGain(Amp_GAIN_02);
    break;

 case 2:
    Amp_SetGain(Amp_GAIN_04);
    break;

 default:
    Amp_SetGain(Amp_GAIN_01);
    break;

}

Finally, we switch the gain on our programmable gain amplifier based on the position of the gain potentiometer. Gain on the PGA is configurable in predefined intervals.

That’s it, Then the whole loop starts over!

Make Some Music

For a demo of the finished project, check out this video:

Resources & Going Further

Hopefully you enjoyed this project write-up! We’re just scraping the surface of the FreeSoC’s capabilities here so feel free to improve on this project and tell us all about your build!

FreeSoC2 Resources

For more audio related fun, check out these other SparkFun tutorials:

SparkPunk Sequencer Theory and Applications Guide

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

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.

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.

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

Viewing all 1123 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>