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

Python and GPS Tracking

$
0
0

Introduction

In my quest to design a radio tracking system for my next HAB, I found it very easy to create applications on my computer and interact with embedded hardware over a serial port using the Python programming language. My goal was to have my HAB transmit GPS data (as well as other sensor data) over RF, to a base station, and graphically display position and altitude on a map. My base station is a radio receiver connected to my laptop over a serial to USB connection. However, in this tutorial, instead of using radios, we will use a GPS tethered to your computer over USB, as a proof of concept.

Of course, with an internet connection, I could easily load my waypoints into many different online tools to view my position on a map, but I didn't want to rely on internet coverage. I wanted the position of the balloon plotted on my own map, so that I could actively track, without the need for internet or paper maps. The program can also be used as a general purpose NMEA parser, that will plot positions on a map of your choice. Just enter your NMEA data into a text file and the program will do the rest.

Showing a trip from SparkFun to Boulder, CO. 

This tutorial will start with a general introduction to Python and Python programming. Once you can run a simple Python script, we move to an example that shows you how to perform a serial loop back test, by creating a stripped down serial terminal program. The loopback test demonstrates how to send and receive serial data through Python, which is the first step to interacting with all kinds of embedded hardware over the serial port. We will finish with a real-world example that takes GPS data over the serial port and plots position overlaid on a scaled map of your choice. If you want to follow along with everything in this tutorial, there are a few pieces of hardware you will need.

For the loopback test, all you need is the FTDI Basic. For the GPS tracking example, you will need a GPS unit, as well as the FTDI. 

What is Python?

If you are already familiar with installing and running Python, feel free to skip ahead. Python is an interpreted programming language, which is slightly different than something like Arduino or programming in C. The program you write isn't compiled as a whole, into machine code, rather each line of the program is sequentially fed into something called a Python interpreter. Once you get the Python interpreter installed, you can write scripts using any text editor. Your program is run by simply calling your Python script and, line by line, your code is fed into the interpreter. If your code has a mistake, the interpreter will stop at that line and give you an error code, along with the line number of the error.

The holy grail for Python 2.7 reference can be found here:

Installing Python

At the time of this tutorial, Python 2.7 is the most widely used version of Python and has the most compatible libraries (aka modules). Python 3 is available, but I suggest sticking with 2.7, if you want the greatest compatibility. 

After you install Python, you should be able to open a command prompt within any directory and type 'python'. You should see the interpreter fire up.

If you don't see this, it is time to start some detective work. Copy your error code, enter it into your search engine along with the name 'python' and your OS name, and then you should see a wealth of solutions to issues similar, if not exact, to yours. Very likely, if the command 'python' is not found, you will need to edit your PATH variables. More information on this can be found here. FYI, be VERY careful editing PATH variables. If you don't do it correctly, you can really mess up your computer, so follow the instructions exactly. You have been warned. 

If you don't want to edit PATH variables, you can always run Python.exe directly out of your Python installation folder.

Running a Python Script 

Once you can invoke the Python interpreter, you can now run a simple test script. Now is a good time to choose a text editor, preferably one that knows you are writing Python code. In Windows, I suggest Programmers Notepad, and in Mac/Linux I use gedit. One of the main rules you need to follow when writing Python code is that code chunks are not enclosed by brackets {}, like they are in C programming. Instead, Python uses tabs to separate code blocks, specifically 4 space tabs. If you don't use 4 space tabs or don't use an editor that tabs correctly, you could get errant formatting, the interpreter will throw errors, and you will no doubt have a bad time. 

For example, here is a simple script that will print 'test' continuously. 

# simple script
def test():
    print "test"
while 1:
    test()

Now save this code in a text editor with the extention your_script_name.py.

The first line is a comment (text that isn't executed) and can be created by using a # .

The second line is a function definition named test().

The third line is spaced 4 times and is the function body, which just prints "test"to the command window.

The third line is where the code starts in a while loop, running the test() function.

To run this script, copy and paste the code into a file and save it with the extention .py. Now open a command line in the directory of your script and type:

python your_script_name.py

The window should see the word 'test' screaming by.

To stop the program, hit Ctrl+c or close the window. 

Installing a Python Module

At some point in your development, you will want to use a library or module that someone else has written. There is a simple process of installing Python modules. The first one we want to install is pyserial.

Download the tar.gz file and un-compress it to an accessible location. Open a command prompt in the location of the pyserial directory and send the command (use sudo if using linux):

python setup.py install

You should see a bunch of action in the command window and hopefully no errors. All this process is doing is moving some files into your main Python installation location, so that when you call the module in your script, Python knows where to find it. You can actually delete the module folder and tar.gz file when you are done, since the relevant source code was just copied to a location in your main Python directory. More information on how this works can be found here:

FYI, many Python modules can be found in Windows .exe installation packages that allow you to forgo the above steps for a 'one-click' installation. A good resource for Windows binary files for 32-bit and 64-bit OS can be found here:

Python Serial Loopback Test

This example requires using an FTDI Basic or any other serial COM port device.

Simply, connect the TX pin to the RX pin with a wire to form a loopback. Anything that gets sent out of the serial port transmit pin gets bounced back to the receive pin. This test proves your serial device works and that you can send and receive data.  

Now, plug your FTDI Basic into your computer and find your COM port number. We can see a list of available ports by typing this:

python -m serial.tools.list_ports

If you are using linux:

dmesg | grep tty

Note your COM port number. 

Now download the piece of code below and open it in a text editor (make sure everything is tabbed in 4 space intervals!!):

import serial

#####Global Variables######################################
#be sure to declare the variable as 'global var' in the fxn
ser = 0

#####FUNCTIONS#############################################
#initialize serial connection 
def init_serial():
    COMNUM = 9 #set you COM port # here
    global ser #must be declared in each fxn used
    ser = serial.Serial()
    ser.baudrate = 9600
    ser.port = COMNUM - 1 #starts at 0, so subtract 1
    #ser.port = '/dev/ttyUSB0' #uncomment for linux

    #you must specify a timeout (in seconds) so that the
    # serial port doesn't hang
    ser.timeout = 1
    ser.open() #open the serial port

    # print port open or closed
    if ser.isOpen():
        print 'Open: ' + ser.portstr
#####SETUP################################################
#this is a good spot to run your initializations 
init_serial()

#####MAIN LOOP############################################
while 1:
    #prints what is sent in on the serial port
    temp = raw_input('Type what you want to send, hit enter:\n\r')
    ser.write(temp) #write to the serial port
    bytes = ser.readline() #reads in bytes followed by a newline 
    print 'You sent: ' + bytes #print to the console
    break #jump out of loop 
#hit ctr-c to close python window

First thing you need to do before running this code is to change the COM port number to the one that is attached to your FTDI. The COMNUM variable in the first few lines is where you enter your COM port number. If you are running linux, read the comments above for ser.port.

Now, if you want to send data over the serial port, use: 

ser.write(your_data)

your_data can be one byte or multiple bytes.

If you want to receive data over the serial port, use:

your_data = ser.readline() 

The readline() function will read in a series of bytes terminated with a new line character (i.e. typing something then hitting enter on your keyboard). This works great with GPS, because each GPS NMEA sentence is terminated with a newline. For more information on how to use pyserial, look here.

You might realize that there are three communication channels being used:

  1. ser.write - writes or transmitts data out of the serial port
  2. ser.read - reads or receives data from the serial port
  3. print - prints to the console window

Just be aware that 'print' does not mean print out to the serial port, it prints to the console window. 

Notice, we don't define the type of variables (i.e. int i = 0). This is because Python treats all variables like strings, which makes parsing text/data very easy. If you need to make calculations, you will need to type cast your variables as floats. An example of this is in the GPS tracking section below.

Now try to run the script by typing (remember you need to be working out of the directory of the pythonGPS.py file):

python pythonGPS.py

This script will open a port and display the port number, then wait for you to enter a string followed by the enter key. If the loopback was successful, you should see what you sent and the program should end with a Python prompt >>>. 

To close the window after successfully running, hit Ctrl + c.

Congratulations! You have just made yourself a very simple serial terminal program that can transmit and receive data!

Read a GPS and plot position with Python

Now that we know how to run a python script and open a serial port, there are many things you can do to create computer applications that communicate with embedded hardware. In this example, I am going to show you a program that reads GPS data over a serial port, saves the data to a txt file; then the data is read from the txt file, parsed, and plotted on a map. 

There are a few steps that need to be followed in order for this program to work.Install the modules in the order below.

Install modules

Use the same module installation process as above or find an executable package. 

The above process worked for me on my W7 machine, but I had to do some extra steps to get it to work on Ubuntu. Same might be said about Macs. With Ubuntu, you will need to completely clean your system of numpy, then build the source for numpy and matplotlib separately, so that you don't mess up all of the dependencies. Here is the process I used for Ubuntu.

Once you have all of these modules installed without errors, you can download my project from github and run the program with a pre-loaded map and GPS NMEA data to see how it works:

Or you can proceed and create your own map and GPS NMEA data.

Select a map

Any map image will work, all you need to know are the bottom left and top right coordinates of the image. The map I used was a screen shot from Google Earth. I set placemarks at each corner and noted the latitude and longitude of each corner. Be sure to use decimal degrees coordinates.

Then I cropped the image around the two points using gimp. The more accurate you crop the image the more accurate your tracking will be. Save the image as 'map.png' and keep it to the side for now.

Hardware Setup

The hardware for this example includes a FTDI Basic and any NMEA capable GPS unit.

EM-406 GPS connected to a FTDI Basic

For the connections, all you need to do is power the GPS with the FTDI basic (3.3V or 5V and GND), then connect the TX pin of the GPS to the RX pin on the FTDI Basic.

It is probably best to allow the GPS to get a lock by leaving it powered for a few minutes before running the program. If the GPS doesn't have a lock when you run the program, the maps will not be generated and you will see the raw NMEA data streaming in the console window. If you don't have a GPS connected and you try to run the program, you will get out-of-bound errors from the parsing. You can verify your GPS is working correctly by opening a serial terminal program.  

Run the program

Here is the main GPS tracking program file:

Save the python script into a folder and drop your map.png file along side maps.py. Here is what your program directory should look like if you have a GPS connected:

The nmea.txt file will automatically be created if you have your GPS connected. If you don't have a GPS connected and you already have NMEA sentences to be displayed, create a file called 'nmea.txt' and drop the data into the file.

Now open maps.py, we will need to edit some variables, so that your map image will scale correctly. 

Edit these variables specific to the top right and bottom left corners of your map. Don't forget to use decimal degree units!

#adjust these values based on your location and map, lat and long are in decimal degrees
TRX = -105.1621     #top right longitude
TRY = 40.0868       #top right latitude
BLX = -105.2898     #bottom left longitude
BLY = 40.0010       #bottom left latitude

Run the program by typing:

python gpsmap.py

The program starts by getting some information from the user.

You will select to either run the program with a GPS device connected or you can load your own GPS NMEA sentences into a file called nmea.txt. Since you have your GPS connected, you will select your COM port and be presented with two mapping options: a position map...

...or an altitude map.

Once you open the serial port to your GPS, the nmea.txt file will automatically be created and raw GPS NMEA data, specifically GPGGA sentences, will be logged in a private thread. When you make a map selection, the nmea.txt file is copied into a file called temp.txt, which is parsed for latitude and longitude (or altitude). The temp.txt file is created to parse the data so that we don't corrupt or happen to change the main nmea.txt log file. 

The maps are generated in their own windows with options to save, zoom, and hover your mouse over points to get fine grain x,y coordinates. 

Also, the maps don't refresh automatically, so as your GPS logs data, you will need to close the map window and run the map generation commands to get new data. If you close the entire Python program, the logging to nmea.txt halts. 

This program isn't finished by any means. I found myself constantly wanting to add features and fix bugs. I binged on Python for a weekend, simply because there are so many modules to work with: GUI tools, interfacing to the web, etc. It is seriously addicting. If you have any modifications or suggestions, please feel free to leave them in the comments below. Thanks for reading!


EL Wire Quickstart Guide

$
0
0

Let it Glow

When it comes to creating projects that glow, nothing beats EL wire. LEDs are fun and all, but EL wire is what all the hip kids are using. Whether you just want to light up your bicycle for an evening cruise or you're creating an entire light up costume for Burning Man, EL wire is a great solution. In this tutorial, we will show you how to experiment with EL wire without having to worry about how to connect it, how to control it, and how to power it. With the right parts, EL wire can be very easy to implement into any project.

Requirements

If you have purchased the SparkFun EL Wire Starter Kit, you should have everything you need to follow along. If you have purchased just a spool of EL wire, the following is a list of suggested parts to help get you started. With these parts, using EL wire can be simple for those who have no electronics experience at all and for those who are extremely knowledgeable but are looking for a quick and easy solution to using EL wire. Before we go into further detail, let's take a look at what parts we should have:

That might not seem like much, but that's all you need to get started with any EL project.

How it Works

EL wire (short for electroluminescent wire) is particularly useful for many reasons. First, it is flexible, allowing you to sew it into clothing, attach it to moving parts, and bend it into any shape you desire. Second, it comes in many different colors, shapes, and sizes. You can get it in wire form (the most typical shape), tape form, or in panels. (For the sake of this tutorial, I will refer to all of these forms simply as EL wire.) All of these can be cut to any shape or size to achieve the desired effect. Just be sure to reseal the ends that have been cut. Last, EL wire is great because it is cool to the touch, even after being on for hours. Hence why it is often seen in clothing applications. The EL product does not heat up because, rather than heating an element to achieve an optical phenomenon, the glowing in EL comes from sending an electrical current through the material, which is comprised of semiconducting mixtures. The electrons flowing through the material create photons, which create the glowing that we see as a result.

Many people ask, "Can't I just hook up EL wire to a battery?"The answer is, no! In order to operate EL wire properly, you must use AC (alternating current) power. This is similar to the power that comes out of your outlets at home, though outlets provide much more current than needed for EL wire. That's where the inverter comes in. The battery pack included in the EL Starter Kit is not just a battery holder. It houses an inverter as well. This inverter takes the DC (direct current) power produced by the batteries and turns it into AC. If you listen very closely to the inverter battery pack while it's on, you will hear a slight hum, similar to what you would hear if you stand under power lines or close to transformer boxes. (Note: SparkFun does not condone hanging out around high voltage areas). With that, it's important to mention that, although the AC power coming from the inverter is not enough to hurt or kill you, it is enough to give you a good shock, so be careful when handling EL products that are powered. As, I mentioned above, you can cut EL wire to any length or shape, but you must reseal the ends you cut. I recommend using hot glue or epoxy to seal cut wire. If you don't reseal, you could end up getting a good jolt.

How to Use It

Using the EL Wire Starter Kit is about as simple as it gets. Simply plug in the male JST connector from your EL wire into one of the two female JST connectors on the inverter battery pack. Make sure there is a solid connection between the two. Take the battery cover off by sliding in the direction indicated on the pack. Place your batteries in the battery pack inverter, and put the cover back on. Click the button on the case, and your EL wire should illuminate. Press it again for a slow blinking effect, and press it once more for a fast blink. This inverter pack allows you to connect two EL products of your choice at a time. You can mix and match colors as well as shapes. You coul have a red panel with blue wire, green tape with a pink wire, or two yellow and purple wires. The possibilities are endless!

If you need a little more explanation, you can check out our demonstaration video. In it, the two different inverters that SparkFun carries are breifly described, and you can see how each color looks when it’s illuminated.

It’s as simple as that. However, if you are looking for more of a challenge, fear not. EL projects can become very complex, very quickly. You may have noticed that the effects are somewhat limited on the inverter, and both products hooked up behave the same when plugged into it. Let’s say you want one color to blink while the other stays solid. You could purchase another inverter battery pack, or you could get one of the many boards out there that are specifically designed to work with EL products. SparkFun carries two such boards, the EL Sequencer and the EL Escudo Dos. Both of these boards are designed to handle many EL products hooked up to them at once, and there are many different effects you can create with both. If you’re looking for something a little more, check out the Wrapping it Up section.

Wrapping it Up

You should now know everything you need to know to get started with EL wire and the EL Wire Starter Kit. If you have any questions or comments please drop them in the box below. For more information on EL products, how to control them, and project ideas, please check out the following links:

Thanks for checking out our tutorial!

Stepper Motor Quickstart Guide

$
0
0

Stepping Up to the Challenge

There are a handful of motors to choose from, and sometimes it’s unclear as to which one will be best suited for your particular application. In this tutorial, we will discuss one of these motors, the stepper motor, and when it best to choose a stepper motor over the alternatives. We will also discuss how to use this motor with the EasyDriver Stepper Motor Driver board, one of the simplest driver boards around.

Stepper

Requirements

Here is a list of recommended items needed to follow along:

How it Works

Stepper motors vary from regular DC motors in that, rather than just spinning in one direction or another, they can spin in very precise increments. Imagine a motor on an RC airplane. The motor spins very fast in on direction or another. You can vary the speed with the amount of power given to the motor, but you cannot tell the propeller to stop at a specific position. Now imagine a printer. There are lots of moving parts inside a printer, including motors. One such motor acts as the paper feed, spinning rollers that move the piece of paper as ink is being printed on it. This motor needs to be able to move the paper an exact distance to be able to print the next line of text or next line of an image. There is another motor attached to a threaded rod that moves the print head back on forth. Again, that threaded rod needs to be moved an exact amount to print one letter after another. This is where stepper motors come in handy.

Stepper motors can move an exact amount of degrees (or steps) when told to do so. This gives you total control over the motor, allowing you to move it to an exact location and hold that position. It does so by powering coils inside the motor for very short periods of time. The trade off is that you have to power the motor all the time to keep it in the position that you desire. We won’t go into too much detail here, but you can check out this Wikipedia article on stepper motors for all the nitty-gritty information. All you need to know for now is that, to move a stepper motor, you tell it to move a certain number of steps in one direction or the other, and tell it the speed at which to step in that direction.

There are numerous varieties of stepper motors as well as driver boards with which to control them. The methods described here can be used to infer how to use other motors and drivers not mentioned in this tutorial. However, it is always recommended that you consult the datasheets and guides of the motors and drivers specific to the models you have.

How to Use it

Here we will discuss how to assemble, hook up and control your motor with firmware uploaded to the Arduino.

Assembly

The simplest way to use the EasyDriver is to attach headers to it for easy insertion onto a breadboard. Alternatively, you could solder the wires straight to the board. These instructions will assume you are using the breadboard method.

The first step is to solder straight male headers to the EasyDriver. Very few of the actual pins on the EasyDriver will be used in this example. However, soldering headers on all the broken out pins is recommended to give the board more stability when attached to a breadboard. A simple method for this is to break off the desired amount of headers, place them in the breadboard in the appropriate locations, place the EasyDriver on top, and then solder all the connections.

alt text

alt text

alt text

Hook-up

Once you have all the headers soldered on, it’s time to hook up the EasyDriver to your Arduino. Using the picture below, make all the necessary connections.

alt text

Note: The small stepper motor looks different than the one pictured. It should have a 4-pin connector on the end. This will be attached to the 4-pin male header facing upward (see picture #3 in Assembly). Because of the nature of this particular stepper, you can hook up the connector in either orientation, i.e. either the black wire on the left or the yellow wire on the left. It will work either way. If you are using a different motor, consult its documentation to find out which wires should go where.

IMPORTANT: Stepper motors require more power than can be supplied by the Arduino. In this example we will be powering the Uno with a 12V external supply. Notice that the power input (M+) on the EasyDriver is attached to the Vin pin on the Arduino. This will allow you to power both the Arduino and the motor with the same power supply.

Firmware

Once you have everything hooked up correctly, you can upload firmware to the Arduino. The following is some very simple example code to get you up and running. There are numerous examples online, as well as a Stepper library included with the Arduino IDE. Feel free to play around with this code, changing values to see what happens, and feel free to explore other code.

/*************************
Joel Bartlett
SparkFun Electronics
December 27, 2012

This code controls a stepper motor with the 
EasyDriver board. It spins forwards and backwards
***************************/
int dirpin = 2;
int steppin = 3;

void setup() 
{
pinMode(dirpin, OUTPUT);
pinMode(steppin, OUTPUT);
}
void loop()
{

  int i;

  digitalWrite(dirpin, LOW);     // Set the direction.
  delay(100);


  for (i = 0; i<4000; i++)       // Iterate for 4000 microsteps.
  {
    digitalWrite(steppin, LOW);  // This LOW to HIGH change is what creates the
    digitalWrite(steppin, HIGH); // "Rising Edge" so the easydriver knows to when to step.
    delayMicroseconds(500);      // This delay time is close to top speed for this
  }                              // particular motor. Any faster the motor stalls.

  digitalWrite(dirpin, HIGH);    // Change direction.
  delay(100);


  for (i = 0; i<4000; i++)       // Iterate for 4000 microsteps
  {
    digitalWrite(steppin, LOW);  // This LOW to HIGH change is what creates the
    digitalWrite(steppin, HIGH); // "Rising Edge" so the easydriver knows to when to step.
    delayMicroseconds(500);      // This delay time is close to top speed for this
  }                              // particular motor. Any faster the motor stalls.

}

Going further

Now that you’ve figured out how to operate your stepper motor at the simplest level, it’s time to take it to the next level. There is a vast amount of information on the web regarding the Easy Driver and stepper motors in general. The best place to look next would be the EasyDriver website. There is also an great tutoral on the bildr website. Another great resource is the EasyDriver Schematic. If you’re curious as to what the other pins on the EasyDriver do, the schematic will give you some insight. Lastly, you can check out one of my projects involving stepper motors, the Arduija. In it, I use stepper motors controlled by EasyDrivers to create an X-Y gantry that moves a Ouija board automatically.

You should be well on your way to adding stepper motors to your next project. If you have any questions, comments or just want to show off your project, drop us a line in the comments below. Happy hacking!

Mono Audio Amplifier Quickstart Guide

$
0
0

This tiny audio amplifier is based on the Texas Instruments TPA2005D1. It can drive an 8-Ohm speaker at up to 1.4 Watts; it won't shake a stadium, but it will provide plenty of volume for your audio projects.

Quickstart

  • Connect your line-level audio input to the IN + and - header.
  • Connect your speaker to the OUT + and - header.
  • Connect 2.5V to 5.5V to the PWR + and - header. (Don't connect anything to the S (shutdown) pin yet.)

Send some audio to the input, and you should hear it on the speaker! If the sound is not loud enough, if you hear buzzing, or if you'd like to add a volume control, read on.

How it works

Traditional audio amplifiers use power transistors to multiply an analog input by a certain gain to produce an analog output. This produces great sound, but the transistors must operate in the intermediate region between on and off. Transistors operate most efficiently when they're fully on or off, and waste a lot of energy as heat when they're run in between.

The class-D amplifier is radically different. At any moment its output transistors are either fully on or fully off, which is very efficient. But this means that the output isn't true audio, it's a digital PWM-like waveform which is mostly on (VCC) for high output values, and mostly off (GND) for low output values.

This PWM signal is clocked at 250kHz, which is much higher than the audio frequencies being encoded (< 20kHz). Because speakers are mechanical devices that can only respond to audio frequencies, the PWM signal is effectively filtered back into the original audio frequencies by the speaker coil itself. All you hear is the music!

Check out the TPA2005D1 datasheet if you'd like to know more about this amplifier.

To use the amplifier

Connect your input source to the IN + and - header. Because the inputs are differential, it technically doesn't matter which direction you connect them, but if one of your inputs is ground or shield, connect that line to the - terminal. (See the Tips below if you're having problems with hum).

Connect your speaker to the OUT + and - header. If you're using one speaker the polarity doesn't matter, but if you'll be using multiple speakers, ensure that you wire them all the same way to avoid phase problems. The speaker can be 4 or 8 Ohms. The maximum output of the amplifier is 1.4 Watts into 8 Ohms. You can drive smaller-wattage speakers with this amplifier, but you should be careful not to turn up the volume too high to avoid damaging the speaker. You can also drive speakers larger than 1.4W at reduced volume. In general, larger speakers will sound much better than smaller speakers; we've had great luck with old automotive speakers.

Connect a power source to the + and - pins. The power source can be from 2.5V to 5.5V, and should be able to source at least 280 milliamps if you want maximum volume. The red LED will illuminate when the board is powered up.

Apply an audio signal to the input, and you should be able to hear it on the speaker. To change the volume, either change the volume of the signal at its source, or add a volume-control potentiometer to the board (instructions below).

Adding a volume control knob

If you wish, you can easily add a 10K volume control potentiometer to this board. The volume control will let you control the volume by reducing the input signal from 100% to 0%. Note that this will not make the amplifier any louder - if you'd like to do that, see changing the gain resistors below. Here's how to add a volume control potentiometer:

Remove the solder from jumper SJ1. This is the small blob of solder within the white brackets on the bottom right of the board. The easiest way to do this is to apply solder wick to the jumper, and heat it with your soldering iron. When you're done, ensure that the two sides are electrically separated from each other.

Now, connect your 10K potentiometer to the three pads on the lower right of the board. The bottom of the board has silkscreen showing the proper connections. You can solder a trimpot with 0.1"-spacing on the pins (such as COM-09806) directly to the board, or you can use wires to connect the board to a larger potentiometer in a chassis, etc.

Note: Potentiometers come in two styles: "linear taper"and "audio (or logarithmic) taper". Audio taper potentiometers have a logarithmic bias that give a more natural feel in audio volume control applications like this one, but linear taper will also work just fine.

How to use the shutdown pin

The SDN* input can be used to turn off the amplifier to save power when it's not being used. When SDN* is disconnected, or connected to a high logic signal (> 2V), the amplifier will function normally. When the SDN* pin is connected to ground or a low logic signal (< 0.8V), the amplifier and LED will turn off. You can use this feature to save power in battery-operated projects.

Changing the gain resistors

The amplifier chip uses two fixed resistors to set the gain, which is how much the input signal will be amplified. On this board, we're using 150K resistors as recommended by the datasheet, for a gain of 2. If you would like the output to be louder, you can install smaller resistors.

The gain equation for this amplifier is 2 * (150K / R). So if you use 100K resistors the gain would be 3, for 50K resistors the gain would be 6, etc. The datasheet states that the smallest value you should use is 15K for a gain of 20, but we've gone down to 3K (gain = 100) with fair results.

The amplifier board has two positions to add your own through-hole resistors. These are within the white rectangles on the top of the board. You do not need to remove the existing surface-mount resistors, just put your through-hole resistors over the top of them. (Leaving the SMD resistors in parallel with the new resistors will slightly reduce the total resistor value, but this is generally not a problem).

For best results, the two gain resistors should be as closely matched as possible. If you have a bag of identical resistors, you might measure them all with a multimeter and pick the two that have the closest resistance.

Tips

The amplifier's output is only designed to be connected to something with a coil (a speaker or magnetic transducer). Since the output is not a true analog signal, you shouldn't expect to use this board as a preamplifier, etc.

The differential inputs of this board are safe to connect directly to floating-ground audio signals such as from the MP3 Shield and MP3 Trigger.

If your audio source and amplifier have different AC power supplies (such as audio coming from a desktop computer), you may hear a loud hum in the output. To fix this, connect a jumper wire between the - side of the audio input and the power supply ground (PWR - header).

Because the amplifier outputs a 250Khz PWM-like signal, it could potentially radiate interference to nearby sensitive circuitry. For this reason, keep the wires between the amplifier and speaker as short as possible.

Questions?

If you have any questions or problems, let us know at techsupport@sparkfun.com and we'll do our best to help you out. We'd also like to hear about the cool projects you're building with our parts!

Have fun!
- Your friends at SparkFun.

Flexiforce Pressure Sensor (25lbs) Quick Start Guide

$
0
0

Introduction

This is a quick how-to explaining everything you need to get started using your Flexiforce Pressure Sensor.  This example uses the 25lb version, but the concepts learned apply to all the Flex sensors.

Flexiforce

Requirements

Necessary hardware to follow this guide:

You'll also need the Arduino IDE for programming.

Hardware

The Flexiforce Pressure Sensor is essentially a variable resistor. When no pressure is applied, the resistance between the two outer leads is incredibly large, probably greater than 10 Mega Ohms (more than my meter can measure). When pressure is applied, the resistance measured between the outer leads lowers until you've reached the max pressure it's intended to measure. In this case that's about 25 lbs of pressure, and the current Flexiforce Pressure sensor I'm using measures about 50K Ohms when given that max amount of pressure.

You can test the range of your sensor using a multimeter. Just attach the two outer leads to the multimeter and set the meter to measure resistance. Then squeeze the sensor and watch the resistance value change.

Now, let's read values with an Arduino. To do this, we create a voltage divider circuit with the Flexiforce sensor and an extra resistor. I picked 1M Ohm in this example because it's about in the middle of the Flexiforce sensor's dynamic range. Many other similar values could work as well.

Connect 5V to one side of the voltage divider, and GND to the other. In the middle, where the Flexiforce sensor and the resistor connect, connect one of the analog-in pins of the Arduino with a jumper wire. In this case I used pin A0. Here is a Fritzing diagram of the setup:

alt text

Fritzing Wiring Diagram

*Note*: The sensor in the image doesn't look exactly the same as the Flexiforce sensor, but very close. The actual Flexiforce sensor has a larger surface area.

Software

Now that you have your circuit wired and ready, it's time to write some very basic Arduino code.  This code is almost exactly the same as Arduino's standard AnalogReadSerial example. Let's take a look to see what it's doing:

 
// Flexiforce quick start example// Reads A0 every 100ms and sends voltage value over serialvoidsetup() 
{
  // Start serial at 9600 baud  Serial.begin(9600); 
}

voidloop() 
{
  // Read the input on analog pin 0:  int sensorValue = analogRead(A0);
  
  // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):  float voltage = sensorValue * (5.0 / 1023.0);
  
  // Print out the value you read:  Serial.println(voltage);
  
  // Wait 100 milliseconds  delay(100);
}

The code is simply running in a small infinite loop every 100ms, or 10 times a second. In each pass through the loop, it measures the voltage on pin A0 and returns a corresponding value between 0 and 1023. 0 represents ground in this case and 1023 indicates A0 is sitting at 5 Volts. For other numbers in between, we can figure out the voltage by multiplying the measured number by the fraction, 5.0 / 1023.0. We then spit this value back over the Serial port, we can watch the values change in real time.

Go ahead and try. Make sure you have the hardware connected correctly. Program the Arduino, open up the Arduino Serial Monitor (make sure it's using 9600 baud), and watch the voltage values change as you press and release the Flexiforce Pressure Sensor.

Conclusion

Now you know how to use the Flexiforce Pressure Sensor. Believe it or not, there are many different analog sensors where you can use what you learned here and collect data the exact same way. Now it's all up to you to use these types of products however you imagine. If you have any other questions or comments, please drop them in the box below. Enjoy!

Python and GPS Tracking

$
0
0

Introduction

In my quest to design a radio tracking system for my next HAB, I found it very easy to create applications on my computer and interact with embedded hardware over a serial port using the Python programming language. My goal was to have my HAB transmit GPS data (as well as other sensor data) over RF, to a base station, and graphically display position and altitude on a map. My base station is a radio receiver connected to my laptop over a serial to USB connection. However, in this tutorial, instead of using radios, we will use a GPS tethered to your computer over USB, as a proof of concept.

Of course, with an internet connection, I could easily load my waypoints into many different online tools to view my position on a map, but I didn't want to rely on internet coverage. I wanted the position of the balloon plotted on my own map, so that I could actively track, without the need for internet or paper maps. The program can also be used as a general purpose NMEA parser, that will plot positions on a map of your choice. Just enter your NMEA data into a text file and the program will do the rest.

Showing a trip from SparkFun to Boulder, CO. 

This tutorial will start with a general introduction to Python and Python programming. Once you can run a simple Python script, we move to an example that shows you how to perform a serial loop back test, by creating a stripped down serial terminal program. The loopback test demonstrates how to send and receive serial data through Python, which is the first step to interacting with all kinds of embedded hardware over the serial port. We will finish with a real-world example that takes GPS data over the serial port and plots position overlaid on a scaled map of your choice. If you want to follow along with everything in this tutorial, there are a few pieces of hardware you will need.

For the loopback test, all you need is the FTDI Basic. For the GPS tracking example, you will need a GPS unit, as well as the FTDI. 

What is Python?

If you are already familiar with installing and running Python, feel free to skip ahead. Python is an interpreted programming language, which is slightly different than something like Arduino or programming in C. The program you write isn't compiled as a whole, into machine code, rather each line of the program is sequentially fed into something called a Python interpreter. Once you get the Python interpreter installed, you can write scripts using any text editor. Your program is run by simply calling your Python script and, line by line, your code is fed into the interpreter. If your code has a mistake, the interpreter will stop at that line and give you an error code, along with the line number of the error.

The holy grail for Python 2.7 reference can be found here:

Installing Python

At the time of this tutorial, Python 2.7 is the most widely used version of Python and has the most compatible libraries (aka modules). Python 3 is available, but I suggest sticking with 2.7, if you want the greatest compatibility. 

After you install Python, you should be able to open a command prompt within any directory and type 'python'. You should see the interpreter fire up.

If you don't see this, it is time to start some detective work. Copy your error code, enter it into your search engine along with the name 'python' and your OS name, and then you should see a wealth of solutions to issues similar, if not exact, to yours. Very likely, if the command 'python' is not found, you will need to edit your PATH variables. More information on this can be found here. FYI, be VERY careful editing PATH variables. If you don't do it correctly, you can really mess up your computer, so follow the instructions exactly. You have been warned. 

If you don't want to edit PATH variables, you can always run Python.exe directly out of your Python installation folder.

Running a Python Script 

Once you can invoke the Python interpreter, you can now run a simple test script. Now is a good time to choose a text editor, preferably one that knows you are writing Python code. In Windows, I suggest Programmers Notepad, and in Mac/Linux I use gedit. One of the main rules you need to follow when writing Python code is that code chunks are not enclosed by brackets {}, like they are in C programming. Instead, Python uses tabs to separate code blocks, specifically 4 space tabs. If you don't use 4 space tabs or don't use an editor that tabs correctly, you could get errant formatting, the interpreter will throw errors, and you will no doubt have a bad time. 

For example, here is a simple script that will print 'test' continuously. 

# simple script
def test():
    print "test"
while 1:
    test()

Now save this code in a text editor with the extention your_script_name.py.

The first line is a comment (text that isn't executed) and can be created by using a # .

The second line is a function definition named test().

The third line is spaced 4 times and is the function body, which just prints "test"to the command window.

The third line is where the code starts in a while loop, running the test() function.

To run this script, copy and paste the code into a file and save it with the extention .py. Now open a command line in the directory of your script and type:

python your_script_name.py

The window should see the word 'test' screaming by.

To stop the program, hit Ctrl+c or close the window. 

Installing a Python Module

At some point in your development, you will want to use a library or module that someone else has written. There is a simple process of installing Python modules. The first one we want to install is pyserial.

Download the tar.gz file and un-compress it to an accessible location. Open a command prompt in the location of the pyserial directory and send the command (use sudo if using linux):

python setup.py install

You should see a bunch of action in the command window and hopefully no errors. All this process is doing is moving some files into your main Python installation location, so that when you call the module in your script, Python knows where to find it. You can actually delete the module folder and tar.gz file when you are done, since the relevant source code was just copied to a location in your main Python directory. More information on how this works can be found here:

FYI, many Python modules can be found in Windows .exe installation packages that allow you to forgo the above steps for a 'one-click' installation. A good resource for Windows binary files for 32-bit and 64-bit OS can be found here:

Python Serial Loopback Test

This example requires using an FTDI Basic or any other serial COM port device.

Simply, connect the TX pin to the RX pin with a wire to form a loopback. Anything that gets sent out of the serial port transmit pin gets bounced back to the receive pin. This test proves your serial device works and that you can send and receive data.  

Now, plug your FTDI Basic into your computer and find your COM port number. We can see a list of available ports by typing this:

python -m serial.tools.list_ports

If you are using linux:

dmesg | grep tty

Note your COM port number. 

Now download the piece of code below and open it in a text editor (make sure everything is tabbed in 4 space intervals!!):

import serial

#####Global Variables######################################
#be sure to declare the variable as 'global var' in the fxn
ser = 0

#####FUNCTIONS#############################################
#initialize serial connection 
def init_serial():
    COMNUM = 9 #set you COM port # here
    global ser #must be declared in each fxn used
    ser = serial.Serial()
    ser.baudrate = 9600
    ser.port = COMNUM - 1 #starts at 0, so subtract 1
    #ser.port = '/dev/ttyUSB0' #uncomment for linux

    #you must specify a timeout (in seconds) so that the
    # serial port doesn't hang
    ser.timeout = 1
    ser.open() #open the serial port

    # print port open or closed
    if ser.isOpen():
        print 'Open: ' + ser.portstr
#####SETUP################################################
#this is a good spot to run your initializations 
init_serial()

#####MAIN LOOP############################################
while 1:
    #prints what is sent in on the serial port
    temp = raw_input('Type what you want to send, hit enter:\n\r')
    ser.write(temp) #write to the serial port
    bytes = ser.readline() #reads in bytes followed by a newline 
    print 'You sent: ' + bytes #print to the console
    break #jump out of loop 
#hit ctr-c to close python window

First thing you need to do before running this code is to change the COM port number to the one that is attached to your FTDI. The COMNUM variable in the first few lines is where you enter your COM port number. If you are running linux, read the comments above for ser.port.

Now, if you want to send data over the serial port, use: 

ser.write(your_data)

your_data can be one byte or multiple bytes.

If you want to receive data over the serial port, use:

your_data = ser.readline() 

The readline() function will read in a series of bytes terminated with a new line character (i.e. typing something then hitting enter on your keyboard). This works great with GPS, because each GPS NMEA sentence is terminated with a newline. For more information on how to use pyserial, look here.

You might realize that there are three communication channels being used:

  1. ser.write - writes or transmitts data out of the serial port
  2. ser.read - reads or receives data from the serial port
  3. print - prints to the console window

Just be aware that 'print' does not mean print out to the serial port, it prints to the console window. 

Notice, we don't define the type of variables (i.e. int i = 0). This is because Python treats all variables like strings, which makes parsing text/data very easy. If you need to make calculations, you will need to type cast your variables as floats. An example of this is in the GPS tracking section below.

Now try to run the script by typing (remember you need to be working out of the directory of the pythonGPS.py file):

python pythonGPS.py

This script will open a port and display the port number, then wait for you to enter a string followed by the enter key. If the loopback was successful, you should see what you sent and the program should end with a Python prompt >>>. 

To close the window after successfully running, hit Ctrl + c.

Congratulations! You have just made yourself a very simple serial terminal program that can transmit and receive data!

Read a GPS and plot position with Python

Now that we know how to run a python script and open a serial port, there are many things you can do to create computer applications that communicate with embedded hardware. In this example, I am going to show you a program that reads GPS data over a serial port, saves the data to a txt file; then the data is read from the txt file, parsed, and plotted on a map. 

There are a few steps that need to be followed in order for this program to work.Install the modules in the order below.

Install modules

Use the same module installation process as above or find an executable package. 

The above process worked for me on my W7 machine, but I had to do some extra steps to get it to work on Ubuntu. Same might be said about Macs. With Ubuntu, you will need to completely clean your system of numpy, then build the source for numpy and matplotlib separately, so that you don't mess up all of the dependencies. Here is the process I used for Ubuntu.

Once you have all of these modules installed without errors, you can download my project from github and run the program with a pre-loaded map and GPS NMEA data to see how it works:

Or you can proceed and create your own map and GPS NMEA data.

Select a map

Any map image will work, all you need to know are the bottom left and top right coordinates of the image. The map I used was a screen shot from Google Earth. I set placemarks at each corner and noted the latitude and longitude of each corner. Be sure to use decimal degrees coordinates.

Then I cropped the image around the two points using gimp. The more accurate you crop the image the more accurate your tracking will be. Save the image as 'map.png' and keep it to the side for now.

Hardware Setup

The hardware for this example includes a FTDI Basic and any NMEA capable GPS unit.

EM-406 GPS connected to a FTDI Basic

For the connections, all you need to do is power the GPS with the FTDI basic (3.3V or 5V and GND), then connect the TX pin of the GPS to the RX pin on the FTDI Basic.

It is probably best to allow the GPS to get a lock by leaving it powered for a few minutes before running the program. If the GPS doesn't have a lock when you run the program, the maps will not be generated and you will see the raw NMEA data streaming in the console window. If you don't have a GPS connected and you try to run the program, you will get out-of-bound errors from the parsing. You can verify your GPS is working correctly by opening a serial terminal program.  

Run the program

Here is the main GPS tracking program file:

Save the python script into a folder and drop your map.png file along side maps.py. Here is what your program directory should look like if you have a GPS connected:

The nmea.txt file will automatically be created if you have your GPS connected. If you don't have a GPS connected and you already have NMEA sentences to be displayed, create a file called 'nmea.txt' and drop the data into the file.

Now open maps.py, we will need to edit some variables, so that your map image will scale correctly. 

Edit these variables specific to the top right and bottom left corners of your map. Don't forget to use decimal degree units!

#adjust these values based on your location and map, lat and long are in decimal degrees
TRX = -105.1621     #top right longitude
TRY = 40.0868       #top right latitude
BLX = -105.2898     #bottom left longitude
BLY = 40.0010       #bottom left latitude

Run the program by typing:

python gpsmap.py

The program starts by getting some information from the user.

You will select to either run the program with a GPS device connected or you can load your own GPS NMEA sentences into a file called nmea.txt. Since you have your GPS connected, you will select your COM port and be presented with two mapping options: a position map...

...or an altitude map.

Once you open the serial port to your GPS, the nmea.txt file will automatically be created and raw GPS NMEA data, specifically GPGGA sentences, will be logged in a private thread. When you make a map selection, the nmea.txt file is copied into a file called temp.txt, which is parsed for latitude and longitude (or altitude). The temp.txt file is created to parse the data so that we don't corrupt or happen to change the main nmea.txt log file. 

The maps are generated in their own windows with options to save, zoom, and hover your mouse over points to get fine grain x,y coordinates. 

Also, the maps don't refresh automatically, so as your GPS logs data, you will need to close the map window and run the map generation commands to get new data. If you close the entire Python program, the logging to nmea.txt halts. 

This program isn't finished by any means. I found myself constantly wanting to add features and fix bugs. I binged on Python for a weekend, simply because there are so many modules to work with: GUI tools, interfacing to the web, etc. It is seriously addicting. If you have any modifications or suggestions, please feel free to leave them in the comments below. Thanks for reading!

EL Wire Quickstart Guide

$
0
0

Let it Glow

When it comes to creating projects that glow, nothing beats EL wire. LEDs are fun and all, but EL wire is what all the hip kids are using. Whether you just want to light up your bicycle for an evening cruise or you're creating an entire light up costume for Burning Man, EL wire is a great solution. In this tutorial, we will show you how to experiment with EL wire without having to worry about how to connect it, how to control it, and how to power it. With the right parts, EL wire can be very easy to implement into any project.

Requirements

If you have purchased the SparkFun EL Wire Starter Kit, you should have everything you need to follow along. If you have purchased just a spool of EL wire, the following is a list of suggested parts to help get you started. With these parts, using EL wire can be simple for those who have no electronics experience at all and for those who are extremely knowledgeable but are looking for a quick and easy solution to using EL wire. Before we go into further detail, let's take a look at what parts we should have:

That might not seem like much, but that's all you need to get started with any EL project.

How it Works

EL wire (short for electroluminescent wire) is particularly useful for many reasons. First, it is flexible, allowing you to sew it into clothing, attach it to moving parts, and bend it into any shape you desire. Second, it comes in many different colors, shapes, and sizes. You can get it in wire form (the most typical shape), tape form, or in panels. (For the sake of this tutorial, I will refer to all of these forms simply as EL wire.) All of these can be cut to any shape or size to achieve the desired effect. Just be sure to reseal the ends that have been cut. Last, EL wire is great because it is cool to the touch, even after being on for hours. Hence why it is often seen in clothing applications. The EL product does not heat up because, rather than heating an element to achieve an optical phenomenon, the glowing in EL comes from sending an electrical current through the material, which is comprised of semiconducting mixtures. The electrons flowing through the material create photons, which create the glowing that we see as a result.

Many people ask, "Can't I just hook up EL wire to a battery?"The answer is, no! In order to operate EL wire properly, you must use AC (alternating current) power. This is similar to the power that comes out of your outlets at home, though outlets provide much more current than needed for EL wire. That's where the inverter comes in. The battery pack included in the EL Starter Kit is not just a battery holder. It houses an inverter as well. This inverter takes the DC (direct current) power produced by the batteries and turns it into AC. If you listen very closely to the inverter battery pack while it's on, you will hear a slight hum, similar to what you would hear if you stand under power lines or close to transformer boxes. (Note: SparkFun does not condone hanging out around high voltage areas). With that, it's important to mention that, although the AC power coming from the inverter is not enough to hurt or kill you, it is enough to give you a good shock, so be careful when handling EL products that are powered. As, I mentioned above, you can cut EL wire to any length or shape, but you must reseal the ends you cut. I recommend using hot glue or epoxy to seal cut wire. If you don't reseal, you could end up getting a good jolt.

How to Use It

Using the EL Wire Starter Kit is about as simple as it gets. Simply plug in the male JST connector from your EL wire into one of the two female JST connectors on the inverter battery pack. Make sure there is a solid connection between the two. Take the battery cover off by sliding in the direction indicated on the pack. Place your batteries in the battery pack inverter, and put the cover back on. Click the button on the case, and your EL wire should illuminate. Press it again for a slow blinking effect, and press it once more for a fast blink. This inverter pack allows you to connect two EL products of your choice at a time. You can mix and match colors as well as shapes. You coul have a red panel with blue wire, green tape with a pink wire, or two yellow and purple wires. The possibilities are endless!

If you need a little more explanation, you can check out our demonstaration video. In it, the two different inverters that SparkFun carries are breifly described, and you can see how each color looks when it’s illuminated.

It’s as simple as that. However, if you are looking for more of a challenge, fear not. EL projects can become very complex, very quickly. You may have noticed that the effects are somewhat limited on the inverter, and both products hooked up behave the same when plugged into it. Let’s say you want one color to blink while the other stays solid. You could purchase another inverter battery pack, or you could get one of the many boards out there that are specifically designed to work with EL products. SparkFun carries two such boards, the EL Sequencer and the EL Escudo Dos. Both of these boards are designed to handle many EL products hooked up to them at once, and there are many different effects you can create with both. If you’re looking for something a little more, check out the Wrapping it Up section.

Wrapping it Up

You should now know everything you need to know to get started with EL wire and the EL Wire Starter Kit. If you have any questions or comments please drop them in the box below. For more information on EL products, how to control them, and project ideas, please check out the following links:

Thanks for checking out our tutorial!

Stepper Motor Quickstart Guide

$
0
0

Stepping Up to the Challenge

There are a handful of motors to choose from, and sometimes it’s unclear as to which one will be best suited for your particular application. In this tutorial, we will discuss one of these motors, the stepper motor, and when it best to choose a stepper motor over the alternatives. We will also discuss how to use this motor with the EasyDriver Stepper Motor Driver board, one of the simplest driver boards around.

Stepper

Requirements

Here is a list of recommended items needed to follow along:

How it Works

Stepper motors vary from regular DC motors in that, rather than just spinning in one direction or another, they can spin in very precise increments. Imagine a motor on an RC airplane. The motor spins very fast in on direction or another. You can vary the speed with the amount of power given to the motor, but you cannot tell the propeller to stop at a specific position. Now imagine a printer. There are lots of moving parts inside a printer, including motors. One such motor acts as the paper feed, spinning rollers that move the piece of paper as ink is being printed on it. This motor needs to be able to move the paper an exact distance to be able to print the next line of text or next line of an image. There is another motor attached to a threaded rod that moves the print head back on forth. Again, that threaded rod needs to be moved an exact amount to print one letter after another. This is where stepper motors come in handy.

Stepper motors can move an exact amount of degrees (or steps) when told to do so. This gives you total control over the motor, allowing you to move it to an exact location and hold that position. It does so by powering coils inside the motor for very short periods of time. The trade off is that you have to power the motor all the time to keep it in the position that you desire. We won’t go into too much detail here, but you can check out this Wikipedia article on stepper motors for all the nitty-gritty information. All you need to know for now is that, to move a stepper motor, you tell it to move a certain number of steps in one direction or the other, and tell it the speed at which to step in that direction.

There are numerous varieties of stepper motors as well as driver boards with which to control them. The methods described here can be used to infer how to use other motors and drivers not mentioned in this tutorial. However, it is always recommended that you consult the datasheets and guides of the motors and drivers specific to the models you have.

How to Use it

Here we will discuss how to assemble, hook up and control your motor with firmware uploaded to the Arduino.

Assembly

The simplest way to use the EasyDriver is to attach headers to it for easy insertion onto a breadboard. Alternatively, you could solder the wires straight to the board. These instructions will assume you are using the breadboard method.

The first step is to solder straight male headers to the EasyDriver. Very few of the actual pins on the EasyDriver will be used in this example. However, soldering headers on all the broken out pins is recommended to give the board more stability when attached to a breadboard. A simple method for this is to break off the desired amount of headers, place them in the breadboard in the appropriate locations, place the EasyDriver on top, and then solder all the connections.

alt text

alt text

alt text

Hook-up

Once you have all the headers soldered on, it’s time to hook up the EasyDriver to your Arduino. Using the picture below, make all the necessary connections.

alt text

Note: The small stepper motor looks different than the one pictured. It should have a 4-pin connector on the end. This will be attached to the 4-pin male header facing upward (see picture #3 in Assembly). Because of the nature of this particular stepper, you can hook up the connector in either orientation, i.e. either the black wire on the left or the yellow wire on the left. It will work either way. If you are using a different motor, consult its documentation to find out which wires should go where.

IMPORTANT: Stepper motors require more power than can be supplied by the Arduino. In this example we will be powering the Uno with a 12V external supply. Notice that the power input (M+) on the EasyDriver is attached to the Vin pin on the Arduino. This will allow you to power both the Arduino and the motor with the same power supply.

Firmware

Once you have everything hooked up correctly, you can upload firmware to the Arduino. The following is some very simple example code to get you up and running. There are numerous examples online, as well as a Stepper library included with the Arduino IDE. Feel free to play around with this code, changing values to see what happens, and feel free to explore other code.

/*************************
Joel Bartlett
SparkFun Electronics
December 27, 2012

This code controls a stepper motor with the 
EasyDriver board. It spins forwards and backwards
***************************/
int dirpin = 2;
int steppin = 3;

void setup() 
{
pinMode(dirpin, OUTPUT);
pinMode(steppin, OUTPUT);
}
void loop()
{

  int i;

  digitalWrite(dirpin, LOW);     // Set the direction.
  delay(100);


  for (i = 0; i<4000; i++)       // Iterate for 4000 microsteps.
  {
    digitalWrite(steppin, LOW);  // This LOW to HIGH change is what creates the
    digitalWrite(steppin, HIGH); // "Rising Edge" so the easydriver knows to when to step.
    delayMicroseconds(500);      // This delay time is close to top speed for this
  }                              // particular motor. Any faster the motor stalls.

  digitalWrite(dirpin, HIGH);    // Change direction.
  delay(100);


  for (i = 0; i<4000; i++)       // Iterate for 4000 microsteps
  {
    digitalWrite(steppin, LOW);  // This LOW to HIGH change is what creates the
    digitalWrite(steppin, HIGH); // "Rising Edge" so the easydriver knows to when to step.
    delayMicroseconds(500);      // This delay time is close to top speed for this
  }                              // particular motor. Any faster the motor stalls.

}

Going further

Now that you’ve figured out how to operate your stepper motor at the simplest level, it’s time to take it to the next level. There is a vast amount of information on the web regarding the Easy Driver and stepper motors in general. The best place to look next would be the EasyDriver website. There is also an great tutoral on the bildr website. Another great resource is the EasyDriver Schematic. If you’re curious as to what the other pins on the EasyDriver do, the schematic will give you some insight. Lastly, you can check out one of my projects involving stepper motors, the Arduija. In it, I use stepper motors controlled by EasyDrivers to create an X-Y gantry that moves a Ouija board automatically.

You should be well on your way to adding stepper motors to your next project. If you have any questions, comments or just want to show off your project, drop us a line in the comments below. Happy hacking!


Mono Audio Amplifier Quickstart Guide

$
0
0

This tiny audio amplifier is based on the Texas Instruments TPA2005D1. It can drive an 8-Ohm speaker at up to 1.4 Watts; it won't shake a stadium, but it will provide plenty of volume for your audio projects.

Quickstart

  • Connect your line-level audio input to the IN + and - header.
  • Connect your speaker to the OUT + and - header.
  • Connect 2.5V to 5.5V to the PWR + and - header. (Don't connect anything to the S (shutdown) pin yet.)

Send some audio to the input, and you should hear it on the speaker! If the sound is not loud enough, if you hear buzzing, or if you'd like to add a volume control, read on.

How it works

Traditional audio amplifiers use power transistors to multiply an analog input by a certain gain to produce an analog output. This produces great sound, but the transistors must operate in the intermediate region between on and off. Transistors operate most efficiently when they're fully on or off, and waste a lot of energy as heat when they're run in between.

The class-D amplifier is radically different. At any moment its output transistors are either fully on or fully off, which is very efficient. But this means that the output isn't true audio, it's a digital PWM-like waveform which is mostly on (VCC) for high output values, and mostly off (GND) for low output values.

This PWM signal is clocked at 250kHz, which is much higher than the audio frequencies being encoded (< 20kHz). Because speakers are mechanical devices that can only respond to audio frequencies, the PWM signal is effectively filtered back into the original audio frequencies by the speaker coil itself. All you hear is the music!

Check out the TPA2005D1 datasheet if you'd like to know more about this amplifier.

To use the amplifier

Connect your input source to the IN + and - header. Because the inputs are differential, it technically doesn't matter which direction you connect them, but if one of your inputs is ground or shield, connect that line to the - terminal. (See the Tips below if you're having problems with hum).

Connect your speaker to the OUT + and - header. If you're using one speaker the polarity doesn't matter, but if you'll be using multiple speakers, ensure that you wire them all the same way to avoid phase problems. The speaker can be 4 or 8 Ohms. The maximum output of the amplifier is 1.4 Watts into 8 Ohms. You can drive smaller-wattage speakers with this amplifier, but you should be careful not to turn up the volume too high to avoid damaging the speaker. You can also drive speakers larger than 1.4W at reduced volume. In general, larger speakers will sound much better than smaller speakers; we've had great luck with old automotive speakers.

Connect a power source to the + and - pins. The power source can be from 2.5V to 5.5V, and should be able to source at least 280 milliamps if you want maximum volume. The red LED will illuminate when the board is powered up.

Apply an audio signal to the input, and you should be able to hear it on the speaker. To change the volume, either change the volume of the signal at its source, or add a volume-control potentiometer to the board (instructions below).

Adding a volume control knob

If you wish, you can easily add a 10K volume control potentiometer to this board. The volume control will let you control the volume by reducing the input signal from 100% to 0%. Note that this will not make the amplifier any louder - if you'd like to do that, see changing the gain resistors below. Here's how to add a volume control potentiometer:

Remove the solder from jumper SJ1. This is the small blob of solder within the white brackets on the bottom right of the board. The easiest way to do this is to apply solder wick to the jumper, and heat it with your soldering iron. When you're done, ensure that the two sides are electrically separated from each other.

Now, connect your 10K potentiometer to the three pads on the lower right of the board. The bottom of the board has silkscreen showing the proper connections. You can solder a trimpot with 0.1"-spacing on the pins (such as COM-09806) directly to the board, or you can use wires to connect the board to a larger potentiometer in a chassis, etc.

Note: Potentiometers come in two styles: "linear taper"and "audio (or logarithmic) taper". Audio taper potentiometers have a logarithmic bias that give a more natural feel in audio volume control applications like this one, but linear taper will also work just fine.

How to use the shutdown pin

The SDN* input can be used to turn off the amplifier to save power when it's not being used. When SDN* is disconnected, or connected to a high logic signal (> 2V), the amplifier will function normally. When the SDN* pin is connected to ground or a low logic signal (< 0.8V), the amplifier and LED will turn off. You can use this feature to save power in battery-operated projects.

Changing the gain resistors

The amplifier chip uses two fixed resistors to set the gain, which is how much the input signal will be amplified. On this board, we're using 150K resistors as recommended by the datasheet, for a gain of 2. If you would like the output to be louder, you can install smaller resistors.

The gain equation for this amplifier is 2 * (150K / R). So if you use 100K resistors the gain would be 3, for 50K resistors the gain would be 6, etc. The datasheet states that the smallest value you should use is 15K for a gain of 20, but we've gone down to 3K (gain = 100) with fair results.

The amplifier board has two positions to add your own through-hole resistors. These are within the white rectangles on the top of the board. You do not need to remove the existing surface-mount resistors, just put your through-hole resistors over the top of them. (Leaving the SMD resistors in parallel with the new resistors will slightly reduce the total resistor value, but this is generally not a problem).

For best results, the two gain resistors should be as closely matched as possible. If you have a bag of identical resistors, you might measure them all with a multimeter and pick the two that have the closest resistance.

Tips

The amplifier's output is only designed to be connected to something with a coil (a speaker or magnetic transducer). Since the output is not a true analog signal, you shouldn't expect to use this board as a preamplifier, etc.

The differential inputs of this board are safe to connect directly to floating-ground audio signals such as from the MP3 Shield and MP3 Trigger.

If your audio source and amplifier have different AC power supplies (such as audio coming from a desktop computer), you may hear a loud hum in the output. To fix this, connect a jumper wire between the - side of the audio input and the power supply ground (PWR - header).

Because the amplifier outputs a 250Khz PWM-like signal, it could potentially radiate interference to nearby sensitive circuitry. For this reason, keep the wires between the amplifier and speaker as short as possible.

Questions?

If you have any questions or problems, let us know at techsupport@sparkfun.com and we'll do our best to help you out. We'd also like to hear about the cool projects you're building with our parts!

Have fun!
- Your friends at SparkFun.

Flexiforce Pressure Sensor (25lbs) Quick Start Guide

$
0
0

Introduction

This is a quick how-to explaining everything you need to get started using your Flexiforce Pressure Sensor.  This example uses the 25lb version, but the concepts learned apply to all the Flex sensors.

Flexiforce

Requirements

Necessary hardware to follow this guide:

You'll also need the Arduino IDE for programming.

Hardware

The Flexiforce Pressure Sensor is essentially a variable resistor. When no pressure is applied, the resistance between the two outer leads is incredibly large, probably greater than 10 Mega Ohms (more than my meter can measure). When pressure is applied, the resistance measured between the outer leads lowers until you've reached the max pressure it's intended to measure. In this case that's about 25 lbs of pressure, and the current Flexiforce Pressure sensor I'm using measures about 50K Ohms when given that max amount of pressure.

You can test the range of your sensor using a multimeter. Just attach the two outer leads to the multimeter and set the meter to measure resistance. Then squeeze the sensor and watch the resistance value change.

Now, let's read values with an Arduino. To do this, we create a voltage divider circuit with the Flexiforce sensor and an extra resistor. I picked 1M Ohm in this example because it's about in the middle of the Flexiforce sensor's dynamic range. Many other similar values could work as well.

Connect 5V to one side of the voltage divider, and GND to the other. In the middle, where the Flexiforce sensor and the resistor connect, connect one of the analog-in pins of the Arduino with a jumper wire. In this case I used pin A0. Here is a Fritzing diagram of the setup:

alt text

Fritzing Wiring Diagram

*Note*: The sensor in the image doesn't look exactly the same as the Flexiforce sensor, but very close. The actual Flexiforce sensor has a larger surface area.

Software

Now that you have your circuit wired and ready, it's time to write some very basic Arduino code.  This code is almost exactly the same as Arduino's standard AnalogReadSerial example. Let's take a look to see what it's doing:

 
// Flexiforce quick start example// Reads A0 every 100ms and sends voltage value over serialvoidsetup() 
{
  // Start serial at 9600 baud  Serial.begin(9600); 
}

voidloop() 
{
  // Read the input on analog pin 0:  int sensorValue = analogRead(A0);
  
  // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):  float voltage = sensorValue * (5.0 / 1023.0);
  
  // Print out the value you read:  Serial.println(voltage);
  
  // Wait 100 milliseconds  delay(100);
}

The code is simply running in a small infinite loop every 100ms, or 10 times a second. In each pass through the loop, it measures the voltage on pin A0 and returns a corresponding value between 0 and 1023. 0 represents ground in this case and 1023 indicates A0 is sitting at 5 Volts. For other numbers in between, we can figure out the voltage by multiplying the measured number by the fraction, 5.0 / 1023.0. We then spit this value back over the Serial port, we can watch the values change in real time.

Go ahead and try. Make sure you have the hardware connected correctly. Program the Arduino, open up the Arduino Serial Monitor (make sure it's using 9600 baud), and watch the voltage values change as you press and release the Flexiforce Pressure Sensor.

Conclusion

Now you know how to use the Flexiforce Pressure Sensor. Believe it or not, there are many different analog sensors where you can use what you learned here and collect data the exact same way. Now it's all up to you to use these types of products however you imagine. If you have any other questions or comments, please drop them in the box below. Enjoy!

Python and GPS Tracking

$
0
0

Introduction

In my quest to design a radio tracking system for my next HAB, I found it very easy to create applications on my computer and interact with embedded hardware over a serial port using the Python programming language. My goal was to have my HAB transmit GPS data (as well as other sensor data) over RF, to a base station, and graphically display position and altitude on a map. My base station is a radio receiver connected to my laptop over a serial to USB connection. However, in this tutorial, instead of using radios, we will use a GPS tethered to your computer over USB, as a proof of concept.

Of course, with an internet connection, I could easily load my waypoints into many different online tools to view my position on a map, but I didn't want to rely on internet coverage. I wanted the position of the balloon plotted on my own map, so that I could actively track, without the need for internet or paper maps. The program can also be used as a general purpose NMEA parser, that will plot positions on a map of your choice. Just enter your NMEA data into a text file and the program will do the rest.

Showing a trip from SparkFun to Boulder, CO. 

This tutorial will start with a general introduction to Python and Python programming. Once you can run a simple Python script, we move to an example that shows you how to perform a serial loop back test, by creating a stripped down serial terminal program. The loopback test demonstrates how to send and receive serial data through Python, which is the first step to interacting with all kinds of embedded hardware over the serial port. We will finish with a real-world example that takes GPS data over the serial port and plots position overlaid on a scaled map of your choice. If you want to follow along with everything in this tutorial, there are a few pieces of hardware you will need.

For the loopback test, all you need is the FTDI Basic. For the GPS tracking example, you will need a GPS unit, as well as the FTDI. 

What is Python?

If you are already familiar with installing and running Python, feel free to skip ahead. Python is an interpreted programming language, which is slightly different than something like Arduino or programming in C. The program you write isn't compiled as a whole, into machine code, rather each line of the program is sequentially fed into something called a Python interpreter. Once you get the Python interpreter installed, you can write scripts using any text editor. Your program is run by simply calling your Python script and, line by line, your code is fed into the interpreter. If your code has a mistake, the interpreter will stop at that line and give you an error code, along with the line number of the error.

The holy grail for Python 2.7 reference can be found here:

Installing Python

At the time of this tutorial, Python 2.7 is the most widely used version of Python and has the most compatible libraries (aka modules). Python 3 is available, but I suggest sticking with 2.7, if you want the greatest compatibility. 

After you install Python, you should be able to open a command prompt within any directory and type 'python'. You should see the interpreter fire up.

If you don't see this, it is time to start some detective work. Copy your error code, enter it into your search engine along with the name 'python' and your OS name, and then you should see a wealth of solutions to issues similar, if not exact, to yours. Very likely, if the command 'python' is not found, you will need to edit your PATH variables. More information on this can be found here. FYI, be VERY careful editing PATH variables. If you don't do it correctly, you can really mess up your computer, so follow the instructions exactly. You have been warned. 

If you don't want to edit PATH variables, you can always run Python.exe directly out of your Python installation folder.

Running a Python Script 

Once you can invoke the Python interpreter, you can now run a simple test script. Now is a good time to choose a text editor, preferably one that knows you are writing Python code. In Windows, I suggest Programmers Notepad, and in Mac/Linux I use gedit. One of the main rules you need to follow when writing Python code is that code chunks are not enclosed by brackets {}, like they are in C programming. Instead, Python uses tabs to separate code blocks, specifically 4 space tabs. If you don't use 4 space tabs or don't use an editor that tabs correctly, you could get errant formatting, the interpreter will throw errors, and you will no doubt have a bad time. 

For example, here is a simple script that will print 'test' continuously. 

# simple script
def test():
    print "test"
while 1:
    test()

Now save this code in a text editor with the extention your_script_name.py.

The first line is a comment (text that isn't executed) and can be created by using a # .

The second line is a function definition named test().

The third line is spaced 4 times and is the function body, which just prints "test"to the command window.

The third line is where the code starts in a while loop, running the test() function.

To run this script, copy and paste the code into a file and save it with the extention .py. Now open a command line in the directory of your script and type:

python your_script_name.py

The window should see the word 'test' screaming by.

To stop the program, hit Ctrl+c or close the window. 

Installing a Python Module

At some point in your development, you will want to use a library or module that someone else has written. There is a simple process of installing Python modules. The first one we want to install is pyserial.

Download the tar.gz file and un-compress it to an accessible location. Open a command prompt in the location of the pyserial directory and send the command (use sudo if using linux):

python setup.py install

You should see a bunch of action in the command window and hopefully no errors. All this process is doing is moving some files into your main Python installation location, so that when you call the module in your script, Python knows where to find it. You can actually delete the module folder and tar.gz file when you are done, since the relevant source code was just copied to a location in your main Python directory. More information on how this works can be found here:

FYI, many Python modules can be found in Windows .exe installation packages that allow you to forgo the above steps for a 'one-click' installation. A good resource for Windows binary files for 32-bit and 64-bit OS can be found here:

Python Serial Loopback Test

This example requires using an FTDI Basic or any other serial COM port device.

Simply, connect the TX pin to the RX pin with a wire to form a loopback. Anything that gets sent out of the serial port transmit pin gets bounced back to the receive pin. This test proves your serial device works and that you can send and receive data.  

Now, plug your FTDI Basic into your computer and find your COM port number. We can see a list of available ports by typing this:

python -m serial.tools.list_ports

If you are using linux:

dmesg | grep tty

Note your COM port number. 

Now download the piece of code below and open it in a text editor (make sure everything is tabbed in 4 space intervals!!):

import serial

#####Global Variables######################################
#be sure to declare the variable as 'global var' in the fxn
ser = 0

#####FUNCTIONS#############################################
#initialize serial connection 
def init_serial():
    COMNUM = 9 #set you COM port # here
    global ser #must be declared in each fxn used
    ser = serial.Serial()
    ser.baudrate = 9600
    ser.port = COMNUM - 1 #starts at 0, so subtract 1
    #ser.port = '/dev/ttyUSB0' #uncomment for linux

    #you must specify a timeout (in seconds) so that the
    # serial port doesn't hang
    ser.timeout = 1
    ser.open() #open the serial port

    # print port open or closed
    if ser.isOpen():
        print 'Open: ' + ser.portstr
#####SETUP################################################
#this is a good spot to run your initializations 
init_serial()

#####MAIN LOOP############################################
while 1:
    #prints what is sent in on the serial port
    temp = raw_input('Type what you want to send, hit enter:\n\r')
    ser.write(temp) #write to the serial port
    bytes = ser.readline() #reads in bytes followed by a newline 
    print 'You sent: ' + bytes #print to the console
    break #jump out of loop 
#hit ctr-c to close python window

First thing you need to do before running this code is to change the COM port number to the one that is attached to your FTDI. The COMNUM variable in the first few lines is where you enter your COM port number. If you are running linux, read the comments above for ser.port.

Now, if you want to send data over the serial port, use: 

ser.write(your_data)

your_data can be one byte or multiple bytes.

If you want to receive data over the serial port, use:

your_data = ser.readline() 

The readline() function will read in a series of bytes terminated with a new line character (i.e. typing something then hitting enter on your keyboard). This works great with GPS, because each GPS NMEA sentence is terminated with a newline. For more information on how to use pyserial, look here.

You might realize that there are three communication channels being used:

  1. ser.write - writes or transmitts data out of the serial port
  2. ser.read - reads or receives data from the serial port
  3. print - prints to the console window

Just be aware that 'print' does not mean print out to the serial port, it prints to the console window. 

Notice, we don't define the type of variables (i.e. int i = 0). This is because Python treats all variables like strings, which makes parsing text/data very easy. If you need to make calculations, you will need to type cast your variables as floats. An example of this is in the GPS tracking section below.

Now try to run the script by typing (remember you need to be working out of the directory of the pythonGPS.py file):

python pythonGPS.py

This script will open a port and display the port number, then wait for you to enter a string followed by the enter key. If the loopback was successful, you should see what you sent and the program should end with a Python prompt >>>. 

To close the window after successfully running, hit Ctrl + c.

Congratulations! You have just made yourself a very simple serial terminal program that can transmit and receive data!

Read a GPS and plot position with Python

Now that we know how to run a python script and open a serial port, there are many things you can do to create computer applications that communicate with embedded hardware. In this example, I am going to show you a program that reads GPS data over a serial port, saves the data to a txt file; then the data is read from the txt file, parsed, and plotted on a map. 

There are a few steps that need to be followed in order for this program to work.Install the modules in the order below.

Install modules

Use the same module installation process as above or find an executable package. 

The above process worked for me on my W7 machine, but I had to do some extra steps to get it to work on Ubuntu. Same might be said about Macs. With Ubuntu, you will need to completely clean your system of numpy, then build the source for numpy and matplotlib separately, so that you don't mess up all of the dependencies. Here is the process I used for Ubuntu.

Once you have all of these modules installed without errors, you can download my project from github and run the program with a pre-loaded map and GPS NMEA data to see how it works:

Or you can proceed and create your own map and GPS NMEA data.

Select a map

Any map image will work, all you need to know are the bottom left and top right coordinates of the image. The map I used was a screen shot from Google Earth. I set placemarks at each corner and noted the latitude and longitude of each corner. Be sure to use decimal degrees coordinates.

Then I cropped the image around the two points using gimp. The more accurate you crop the image the more accurate your tracking will be. Save the image as 'map.png' and keep it to the side for now.

Hardware Setup

The hardware for this example includes a FTDI Basic and any NMEA capable GPS unit.

EM-406 GPS connected to a FTDI Basic

For the connections, all you need to do is power the GPS with the FTDI basic (3.3V or 5V and GND), then connect the TX pin of the GPS to the RX pin on the FTDI Basic.

It is probably best to allow the GPS to get a lock by leaving it powered for a few minutes before running the program. If the GPS doesn't have a lock when you run the program, the maps will not be generated and you will see the raw NMEA data streaming in the console window. If you don't have a GPS connected and you try to run the program, you will get out-of-bound errors from the parsing. You can verify your GPS is working correctly by opening a serial terminal program.  

Run the program

Here is the main GPS tracking program file:

Save the python script into a folder and drop your map.png file along side maps.py. Here is what your program directory should look like if you have a GPS connected:

The nmea.txt file will automatically be created if you have your GPS connected. If you don't have a GPS connected and you already have NMEA sentences to be displayed, create a file called 'nmea.txt' and drop the data into the file.

Now open maps.py, we will need to edit some variables, so that your map image will scale correctly. 

Edit these variables specific to the top right and bottom left corners of your map. Don't forget to use decimal degree units!

#adjust these values based on your location and map, lat and long are in decimal degrees
TRX = -105.1621     #top right longitude
TRY = 40.0868       #top right latitude
BLX = -105.2898     #bottom left longitude
BLY = 40.0010       #bottom left latitude

Run the program by typing:

python gpsmap.py

The program starts by getting some information from the user.

You will select to either run the program with a GPS device connected or you can load your own GPS NMEA sentences into a file called nmea.txt. Since you have your GPS connected, you will select your COM port and be presented with two mapping options: a position map...

...or an altitude map.

Once you open the serial port to your GPS, the nmea.txt file will automatically be created and raw GPS NMEA data, specifically GPGGA sentences, will be logged in a private thread. When you make a map selection, the nmea.txt file is copied into a file called temp.txt, which is parsed for latitude and longitude (or altitude). The temp.txt file is created to parse the data so that we don't corrupt or happen to change the main nmea.txt log file. 

The maps are generated in their own windows with options to save, zoom, and hover your mouse over points to get fine grain x,y coordinates. 

Also, the maps don't refresh automatically, so as your GPS logs data, you will need to close the map window and run the map generation commands to get new data. If you close the entire Python program, the logging to nmea.txt halts. 

This program isn't finished by any means. I found myself constantly wanting to add features and fix bugs. I binged on Python for a weekend, simply because there are so many modules to work with: GUI tools, interfacing to the web, etc. It is seriously addicting. If you have any modifications or suggestions, please feel free to leave them in the comments below. Thanks for reading!

EL Wire Quickstart Guide

$
0
0

Let it Glow

When it comes to creating projects that glow, nothing beats EL wire. LEDs are fun and all, but EL wire is what all the hip kids are using. Whether you just want to light up your bicycle for an evening cruise or you're creating an entire light up costume for Burning Man, EL wire is a great solution. In this tutorial, we will show you how to experiment with EL wire without having to worry about how to connect it, how to control it, and how to power it. With the right parts, EL wire can be very easy to implement into any project.

Requirements

If you have purchased the SparkFun EL Wire Starter Kit, you should have everything you need to follow along. If you have purchased just a spool of EL wire, the following is a list of suggested parts to help get you started. With these parts, using EL wire can be simple for those who have no electronics experience at all and for those who are extremely knowledgeable but are looking for a quick and easy solution to using EL wire. Before we go into further detail, let's take a look at what parts we should have:

That might not seem like much, but that's all you need to get started with any EL project.

How it Works

EL wire (short for electroluminescent wire) is particularly useful for many reasons. First, it is flexible, allowing you to sew it into clothing, attach it to moving parts, and bend it into any shape you desire. Second, it comes in many different colors, shapes, and sizes. You can get it in wire form (the most typical shape), tape form, or in panels. (For the sake of this tutorial, I will refer to all of these forms simply as EL wire.) All of these can be cut to any shape or size to achieve the desired effect. Just be sure to reseal the ends that have been cut. Last, EL wire is great because it is cool to the touch, even after being on for hours. Hence why it is often seen in clothing applications. The EL product does not heat up because, rather than heating an element to achieve an optical phenomenon, the glowing in EL comes from sending an electrical current through the material, which is comprised of semiconducting mixtures. The electrons flowing through the material create photons, which create the glowing that we see as a result.

Many people ask, "Can't I just hook up EL wire to a battery?"The answer is, no! In order to operate EL wire properly, you must use AC (alternating current) power. This is similar to the power that comes out of your outlets at home, though outlets provide much more current than needed for EL wire. That's where the inverter comes in. The battery pack included in the EL Starter Kit is not just a battery holder. It houses an inverter as well. This inverter takes the DC (direct current) power produced by the batteries and turns it into AC. If you listen very closely to the inverter battery pack while it's on, you will hear a slight hum, similar to what you would hear if you stand under power lines or close to transformer boxes. (Note: SparkFun does not condone hanging out around high voltage areas). With that, it's important to mention that, although the AC power coming from the inverter is not enough to hurt or kill you, it is enough to give you a good shock, so be careful when handling EL products that are powered. As, I mentioned above, you can cut EL wire to any length or shape, but you must reseal the ends you cut. I recommend using hot glue or epoxy to seal cut wire. If you don't reseal, you could end up getting a good jolt.

How to Use It

Using the EL Wire Starter Kit is about as simple as it gets. Simply plug in the male JST connector from your EL wire into one of the two female JST connectors on the inverter battery pack. Make sure there is a solid connection between the two. Take the battery cover off by sliding in the direction indicated on the pack. Place your batteries in the battery pack inverter, and put the cover back on. Click the button on the case, and your EL wire should illuminate. Press it again for a slow blinking effect, and press it once more for a fast blink. This inverter pack allows you to connect two EL products of your choice at a time. You can mix and match colors as well as shapes. You coul have a red panel with blue wire, green tape with a pink wire, or two yellow and purple wires. The possibilities are endless!

If you need a little more explanation, you can check out our demonstaration video. In it, the two different inverters that SparkFun carries are breifly described, and you can see how each color looks when it’s illuminated.

It’s as simple as that. However, if you are looking for more of a challenge, fear not. EL projects can become very complex, very quickly. You may have noticed that the effects are somewhat limited on the inverter, and both products hooked up behave the same when plugged into it. Let’s say you want one color to blink while the other stays solid. You could purchase another inverter battery pack, or you could get one of the many boards out there that are specifically designed to work with EL products. SparkFun carries two such boards, the EL Sequencer and the EL Escudo Dos. Both of these boards are designed to handle many EL products hooked up to them at once, and there are many different effects you can create with both. If you’re looking for something a little more, check out the Wrapping it Up section.

Wrapping it Up

You should now know everything you need to know to get started with EL wire and the EL Wire Starter Kit. If you have any questions or comments please drop them in the box below. For more information on EL products, how to control them, and project ideas, please check out the following links:

Thanks for checking out our tutorial!

Stepper Motor Quickstart Guide

$
0
0

Stepping Up to the Challenge

There are a handful of motors to choose from, and sometimes it’s unclear as to which one will be best suited for your particular application. In this tutorial, we will discuss one of these motors, the stepper motor, and when it best to choose a stepper motor over the alternatives. We will also discuss how to use this motor with the EasyDriver Stepper Motor Driver board, one of the simplest driver boards around.

Stepper

Requirements

Here is a list of recommended items needed to follow along:

How it Works

Stepper motors vary from regular DC motors in that, rather than just spinning in one direction or another, they can spin in very precise increments. Imagine a motor on an RC airplane. The motor spins very fast in on direction or another. You can vary the speed with the amount of power given to the motor, but you cannot tell the propeller to stop at a specific position. Now imagine a printer. There are lots of moving parts inside a printer, including motors. One such motor acts as the paper feed, spinning rollers that move the piece of paper as ink is being printed on it. This motor needs to be able to move the paper an exact distance to be able to print the next line of text or next line of an image. There is another motor attached to a threaded rod that moves the print head back on forth. Again, that threaded rod needs to be moved an exact amount to print one letter after another. This is where stepper motors come in handy.

Stepper motors can move an exact amount of degrees (or steps) when told to do so. This gives you total control over the motor, allowing you to move it to an exact location and hold that position. It does so by powering coils inside the motor for very short periods of time. The trade off is that you have to power the motor all the time to keep it in the position that you desire. We won’t go into too much detail here, but you can check out this Wikipedia article on stepper motors for all the nitty-gritty information. All you need to know for now is that, to move a stepper motor, you tell it to move a certain number of steps in one direction or the other, and tell it the speed at which to step in that direction.

There are numerous varieties of stepper motors as well as driver boards with which to control them. The methods described here can be used to infer how to use other motors and drivers not mentioned in this tutorial. However, it is always recommended that you consult the datasheets and guides of the motors and drivers specific to the models you have.

How to Use it

Here we will discuss how to assemble, hook up and control your motor with firmware uploaded to the Arduino.

Assembly

The simplest way to use the EasyDriver is to attach headers to it for easy insertion onto a breadboard. Alternatively, you could solder the wires straight to the board. These instructions will assume you are using the breadboard method.

The first step is to solder straight male headers to the EasyDriver. Very few of the actual pins on the EasyDriver will be used in this example. However, soldering headers on all the broken out pins is recommended to give the board more stability when attached to a breadboard. A simple method for this is to break off the desired amount of headers, place them in the breadboard in the appropriate locations, place the EasyDriver on top, and then solder all the connections.

alt text

alt text

alt text

Hook-up

Once you have all the headers soldered on, it’s time to hook up the EasyDriver to your Arduino. Using the picture below, make all the necessary connections.

alt text

Note: The small stepper motor looks different than the one pictured. It should have a 4-pin connector on the end. This will be attached to the 4-pin male header facing upward (see picture #3 in Assembly). Because of the nature of this particular stepper, you can hook up the connector in either orientation, i.e. either the black wire on the left or the yellow wire on the left. It will work either way. If you are using a different motor, consult its documentation to find out which wires should go where.

IMPORTANT: Stepper motors require more power than can be supplied by the Arduino. In this example we will be powering the Uno with a 12V external supply. Notice that the power input (M+) on the EasyDriver is attached to the Vin pin on the Arduino. This will allow you to power both the Arduino and the motor with the same power supply.

Firmware

Once you have everything hooked up correctly, you can upload firmware to the Arduino. The following is some very simple example code to get you up and running. There are numerous examples online, as well as a Stepper library included with the Arduino IDE. Feel free to play around with this code, changing values to see what happens, and feel free to explore other code.

/*************************
Joel Bartlett
SparkFun Electronics
December 27, 2012

This code controls a stepper motor with the 
EasyDriver board. It spins forwards and backwards
***************************/
int dirpin = 2;
int steppin = 3;

void setup() 
{
pinMode(dirpin, OUTPUT);
pinMode(steppin, OUTPUT);
}
void loop()
{

  int i;

  digitalWrite(dirpin, LOW);     // Set the direction.
  delay(100);


  for (i = 0; i<4000; i++)       // Iterate for 4000 microsteps.
  {
    digitalWrite(steppin, LOW);  // This LOW to HIGH change is what creates the
    digitalWrite(steppin, HIGH); // "Rising Edge" so the easydriver knows to when to step.
    delayMicroseconds(500);      // This delay time is close to top speed for this
  }                              // particular motor. Any faster the motor stalls.

  digitalWrite(dirpin, HIGH);    // Change direction.
  delay(100);


  for (i = 0; i<4000; i++)       // Iterate for 4000 microsteps
  {
    digitalWrite(steppin, LOW);  // This LOW to HIGH change is what creates the
    digitalWrite(steppin, HIGH); // "Rising Edge" so the easydriver knows to when to step.
    delayMicroseconds(500);      // This delay time is close to top speed for this
  }                              // particular motor. Any faster the motor stalls.

}

Going further

Now that you’ve figured out how to operate your stepper motor at the simplest level, it’s time to take it to the next level. There is a vast amount of information on the web regarding the Easy Driver and stepper motors in general. The best place to look next would be the EasyDriver website. There is also an great tutoral on the bildr website. Another great resource is the EasyDriver Schematic. If you’re curious as to what the other pins on the EasyDriver do, the schematic will give you some insight. Lastly, you can check out one of my projects involving stepper motors, the Arduija. In it, I use stepper motors controlled by EasyDrivers to create an X-Y gantry that moves a Ouija board automatically.

You should be well on your way to adding stepper motors to your next project. If you have any questions, comments or just want to show off your project, drop us a line in the comments below. Happy hacking!

Mono Audio Amplifier Quickstart Guide

$
0
0

This tiny audio amplifier is based on the Texas Instruments TPA2005D1. It can drive an 8-Ohm speaker at up to 1.4 Watts; it won't shake a stadium, but it will provide plenty of volume for your audio projects.

Quickstart

  • Connect your line-level audio input to the IN + and - header.
  • Connect your speaker to the OUT + and - header.
  • Connect 2.5V to 5.5V to the PWR + and - header. (Don't connect anything to the S (shutdown) pin yet.)

Send some audio to the input, and you should hear it on the speaker! If the sound is not loud enough, if you hear buzzing, or if you'd like to add a volume control, read on.

How it works

Traditional audio amplifiers use power transistors to multiply an analog input by a certain gain to produce an analog output. This produces great sound, but the transistors must operate in the intermediate region between on and off. Transistors operate most efficiently when they're fully on or off, and waste a lot of energy as heat when they're run in between.

The class-D amplifier is radically different. At any moment its output transistors are either fully on or fully off, which is very efficient. But this means that the output isn't true audio, it's a digital PWM-like waveform which is mostly on (VCC) for high output values, and mostly off (GND) for low output values.

This PWM signal is clocked at 250kHz, which is much higher than the audio frequencies being encoded (< 20kHz). Because speakers are mechanical devices that can only respond to audio frequencies, the PWM signal is effectively filtered back into the original audio frequencies by the speaker coil itself. All you hear is the music!

Check out the TPA2005D1 datasheet if you'd like to know more about this amplifier.

To use the amplifier

Connect your input source to the IN + and - header. Because the inputs are differential, it technically doesn't matter which direction you connect them, but if one of your inputs is ground or shield, connect that line to the - terminal. (See the Tips below if you're having problems with hum).

Connect your speaker to the OUT + and - header. If you're using one speaker the polarity doesn't matter, but if you'll be using multiple speakers, ensure that you wire them all the same way to avoid phase problems. The speaker can be 4 or 8 Ohms. The maximum output of the amplifier is 1.4 Watts into 8 Ohms. You can drive smaller-wattage speakers with this amplifier, but you should be careful not to turn up the volume too high to avoid damaging the speaker. You can also drive speakers larger than 1.4W at reduced volume. In general, larger speakers will sound much better than smaller speakers; we've had great luck with old automotive speakers.

Connect a power source to the + and - pins. The power source can be from 2.5V to 5.5V, and should be able to source at least 280 milliamps if you want maximum volume. The red LED will illuminate when the board is powered up.

Apply an audio signal to the input, and you should be able to hear it on the speaker. To change the volume, either change the volume of the signal at its source, or add a volume-control potentiometer to the board (instructions below).

Adding a volume control knob

If you wish, you can easily add a 10K volume control potentiometer to this board. The volume control will let you control the volume by reducing the input signal from 100% to 0%. Note that this will not make the amplifier any louder - if you'd like to do that, see changing the gain resistors below. Here's how to add a volume control potentiometer:

Remove the solder from jumper SJ1. This is the small blob of solder within the white brackets on the bottom right of the board. The easiest way to do this is to apply solder wick to the jumper, and heat it with your soldering iron. When you're done, ensure that the two sides are electrically separated from each other.

Now, connect your 10K potentiometer to the three pads on the lower right of the board. The bottom of the board has silkscreen showing the proper connections. You can solder a trimpot with 0.1"-spacing on the pins (such as COM-09806) directly to the board, or you can use wires to connect the board to a larger potentiometer in a chassis, etc.

Note: Potentiometers come in two styles: "linear taper"and "audio (or logarithmic) taper". Audio taper potentiometers have a logarithmic bias that give a more natural feel in audio volume control applications like this one, but linear taper will also work just fine.

How to use the shutdown pin

The SDN* input can be used to turn off the amplifier to save power when it's not being used. When SDN* is disconnected, or connected to a high logic signal (> 2V), the amplifier will function normally. When the SDN* pin is connected to ground or a low logic signal (< 0.8V), the amplifier and LED will turn off. You can use this feature to save power in battery-operated projects.

Changing the gain resistors

The amplifier chip uses two fixed resistors to set the gain, which is how much the input signal will be amplified. On this board, we're using 150K resistors as recommended by the datasheet, for a gain of 2. If you would like the output to be louder, you can install smaller resistors.

The gain equation for this amplifier is 2 * (150K / R). So if you use 100K resistors the gain would be 3, for 50K resistors the gain would be 6, etc. The datasheet states that the smallest value you should use is 15K for a gain of 20, but we've gone down to 3K (gain = 100) with fair results.

The amplifier board has two positions to add your own through-hole resistors. These are within the white rectangles on the top of the board. You do not need to remove the existing surface-mount resistors, just put your through-hole resistors over the top of them. (Leaving the SMD resistors in parallel with the new resistors will slightly reduce the total resistor value, but this is generally not a problem).

For best results, the two gain resistors should be as closely matched as possible. If you have a bag of identical resistors, you might measure them all with a multimeter and pick the two that have the closest resistance.

Tips

The amplifier's output is only designed to be connected to something with a coil (a speaker or magnetic transducer). Since the output is not a true analog signal, you shouldn't expect to use this board as a preamplifier, etc.

The differential inputs of this board are safe to connect directly to floating-ground audio signals such as from the MP3 Shield and MP3 Trigger.

If your audio source and amplifier have different AC power supplies (such as audio coming from a desktop computer), you may hear a loud hum in the output. To fix this, connect a jumper wire between the - side of the audio input and the power supply ground (PWR - header).

Because the amplifier outputs a 250Khz PWM-like signal, it could potentially radiate interference to nearby sensitive circuitry. For this reason, keep the wires between the amplifier and speaker as short as possible.

Questions?

If you have any questions or problems, let us know at techsupport@sparkfun.com and we'll do our best to help you out. We'd also like to hear about the cool projects you're building with our parts!

Have fun!
- Your friends at SparkFun.

Flexiforce Pressure Sensor (25lbs) Quick Start Guide

$
0
0

Introduction

This is a quick how-to explaining everything you need to get started using your Flexiforce Pressure Sensor.  This example uses the 25lb version, but the concepts learned apply to all the Flex sensors.

Flexiforce

Requirements

Necessary hardware to follow this guide:

You'll also need the Arduino IDE for programming.

Hardware

The Flexiforce Pressure Sensor is essentially a variable resistor. When no pressure is applied, the resistance between the two outer leads is incredibly large, probably greater than 10 Mega Ohms (more than my meter can measure). When pressure is applied, the resistance measured between the outer leads lowers until you've reached the max pressure it's intended to measure. In this case that's about 25 lbs of pressure, and the current Flexiforce Pressure sensor I'm using measures about 50K Ohms when given that max amount of pressure.

You can test the range of your sensor using a multimeter. Just attach the two outer leads to the multimeter and set the meter to measure resistance. Then squeeze the sensor and watch the resistance value change.

Now, let's read values with an Arduino. To do this, we create a voltage divider circuit with the Flexiforce sensor and an extra resistor. I picked 1M Ohm in this example because it's about in the middle of the Flexiforce sensor's dynamic range. Many other similar values could work as well.

Connect 5V to one side of the voltage divider, and GND to the other. In the middle, where the Flexiforce sensor and the resistor connect, connect one of the analog-in pins of the Arduino with a jumper wire. In this case I used pin A0. Here is a Fritzing diagram of the setup:

alt text

Fritzing Wiring Diagram

*Note*: The sensor in the image doesn't look exactly the same as the Flexiforce sensor, but very close. The actual Flexiforce sensor has a larger surface area.

Software

Now that you have your circuit wired and ready, it's time to write some very basic Arduino code.  This code is almost exactly the same as Arduino's standard AnalogReadSerial example. Let's take a look to see what it's doing:

 
// Flexiforce quick start example// Reads A0 every 100ms and sends voltage value over serialvoidsetup() 
{
  // Start serial at 9600 baud  Serial.begin(9600); 
}

voidloop() 
{
  // Read the input on analog pin 0:  int sensorValue = analogRead(A0);
  
  // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):  float voltage = sensorValue * (5.0 / 1023.0);
  
  // Print out the value you read:  Serial.println(voltage);
  
  // Wait 100 milliseconds  delay(100);
}

The code is simply running in a small infinite loop every 100ms, or 10 times a second. In each pass through the loop, it measures the voltage on pin A0 and returns a corresponding value between 0 and 1023. 0 represents ground in this case and 1023 indicates A0 is sitting at 5 Volts. For other numbers in between, we can figure out the voltage by multiplying the measured number by the fraction, 5.0 / 1023.0. We then spit this value back over the Serial port, we can watch the values change in real time.

Go ahead and try. Make sure you have the hardware connected correctly. Program the Arduino, open up the Arduino Serial Monitor (make sure it's using 9600 baud), and watch the voltage values change as you press and release the Flexiforce Pressure Sensor.

Conclusion

Now you know how to use the Flexiforce Pressure Sensor. Believe it or not, there are many different analog sensors where you can use what you learned here and collect data the exact same way. Now it's all up to you to use these types of products however you imagine. If you have any other questions or comments, please drop them in the box below. Enjoy!


Python and GPS Tracking

$
0
0

Introduction

In my quest to design a radio tracking system for my next HAB, I found it very easy to create applications on my computer and interact with embedded hardware over a serial port using the Python programming language. My goal was to have my HAB transmit GPS data (as well as other sensor data) over RF, to a base station, and graphically display position and altitude on a map. My base station is a radio receiver connected to my laptop over a serial to USB connection. However, in this tutorial, instead of using radios, we will use a GPS tethered to your computer over USB, as a proof of concept.

Of course, with an internet connection, I could easily load my waypoints into many different online tools to view my position on a map, but I didn't want to rely on internet coverage. I wanted the position of the balloon plotted on my own map, so that I could actively track, without the need for internet or paper maps. The program can also be used as a general purpose NMEA parser, that will plot positions on a map of your choice. Just enter your NMEA data into a text file and the program will do the rest.

Showing a trip from SparkFun to Boulder, CO. 

This tutorial will start with a general introduction to Python and Python programming. Once you can run a simple Python script, we move to an example that shows you how to perform a serial loop back test, by creating a stripped down serial terminal program. The loopback test demonstrates how to send and receive serial data through Python, which is the first step to interacting with all kinds of embedded hardware over the serial port. We will finish with a real-world example that takes GPS data over the serial port and plots position overlaid on a scaled map of your choice. If you want to follow along with everything in this tutorial, there are a few pieces of hardware you will need.

For the loopback test, all you need is the FTDI Basic. For the GPS tracking example, you will need a GPS unit, as well as the FTDI. 

What is Python?

If you are already familiar with installing and running Python, feel free to skip ahead. Python is an interpreted programming language, which is slightly different than something like Arduino or programming in C. The program you write isn't compiled as a whole, into machine code, rather each line of the program is sequentially fed into something called a Python interpreter. Once you get the Python interpreter installed, you can write scripts using any text editor. Your program is run by simply calling your Python script and, line by line, your code is fed into the interpreter. If your code has a mistake, the interpreter will stop at that line and give you an error code, along with the line number of the error.

The holy grail for Python 2.7 reference can be found here:

Installing Python

At the time of this tutorial, Python 2.7 is the most widely used version of Python and has the most compatible libraries (aka modules). Python 3 is available, but I suggest sticking with 2.7, if you want the greatest compatibility. 

After you install Python, you should be able to open a command prompt within any directory and type 'python'. You should see the interpreter fire up.

If you don't see this, it is time to start some detective work. Copy your error code, enter it into your search engine along with the name 'python' and your OS name, and then you should see a wealth of solutions to issues similar, if not exact, to yours. Very likely, if the command 'python' is not found, you will need to edit your PATH variables. More information on this can be found here. FYI, be VERY careful editing PATH variables. If you don't do it correctly, you can really mess up your computer, so follow the instructions exactly. You have been warned. 

If you don't want to edit PATH variables, you can always run Python.exe directly out of your Python installation folder.

Running a Python Script 

Once you can invoke the Python interpreter, you can now run a simple test script. Now is a good time to choose a text editor, preferably one that knows you are writing Python code. In Windows, I suggest Programmers Notepad, and in Mac/Linux I use gedit. One of the main rules you need to follow when writing Python code is that code chunks are not enclosed by brackets {}, like they are in C programming. Instead, Python uses tabs to separate code blocks, specifically 4 space tabs. If you don't use 4 space tabs or don't use an editor that tabs correctly, you could get errant formatting, the interpreter will throw errors, and you will no doubt have a bad time. 

For example, here is a simple script that will print 'test' continuously. 

# simple script
def test():
    print "test"
while 1:
    test()

Now save this code in a text editor with the extention your_script_name.py.

The first line is a comment (text that isn't executed) and can be created by using a # .

The second line is a function definition named test().

The third line is spaced 4 times and is the function body, which just prints "test"to the command window.

The third line is where the code starts in a while loop, running the test() function.

To run this script, copy and paste the code into a file and save it with the extention .py. Now open a command line in the directory of your script and type:

python your_script_name.py

The window should see the word 'test' screaming by.

To stop the program, hit Ctrl+c or close the window. 

Installing a Python Module

At some point in your development, you will want to use a library or module that someone else has written. There is a simple process of installing Python modules. The first one we want to install is pyserial.

Download the tar.gz file and un-compress it to an accessible location. Open a command prompt in the location of the pyserial directory and send the command (use sudo if using linux):

python setup.py install

You should see a bunch of action in the command window and hopefully no errors. All this process is doing is moving some files into your main Python installation location, so that when you call the module in your script, Python knows where to find it. You can actually delete the module folder and tar.gz file when you are done, since the relevant source code was just copied to a location in your main Python directory. More information on how this works can be found here:

FYI, many Python modules can be found in Windows .exe installation packages that allow you to forgo the above steps for a 'one-click' installation. A good resource for Windows binary files for 32-bit and 64-bit OS can be found here:

Python Serial Loopback Test

This example requires using an FTDI Basic or any other serial COM port device.

Simply, connect the TX pin to the RX pin with a wire to form a loopback. Anything that gets sent out of the serial port transmit pin gets bounced back to the receive pin. This test proves your serial device works and that you can send and receive data.  

Now, plug your FTDI Basic into your computer and find your COM port number. We can see a list of available ports by typing this:

python -m serial.tools.list_ports

If you are using linux:

dmesg | grep tty

Note your COM port number. 

Now download the piece of code below and open it in a text editor (make sure everything is tabbed in 4 space intervals!!):

import serial

#####Global Variables######################################
#be sure to declare the variable as 'global var' in the fxn
ser = 0

#####FUNCTIONS#############################################
#initialize serial connection 
def init_serial():
    COMNUM = 9 #set you COM port # here
    global ser #must be declared in each fxn used
    ser = serial.Serial()
    ser.baudrate = 9600
    ser.port = COMNUM - 1 #starts at 0, so subtract 1
    #ser.port = '/dev/ttyUSB0' #uncomment for linux

    #you must specify a timeout (in seconds) so that the
    # serial port doesn't hang
    ser.timeout = 1
    ser.open() #open the serial port

    # print port open or closed
    if ser.isOpen():
        print 'Open: ' + ser.portstr
#####SETUP################################################
#this is a good spot to run your initializations 
init_serial()

#####MAIN LOOP############################################
while 1:
    #prints what is sent in on the serial port
    temp = raw_input('Type what you want to send, hit enter:\n\r')
    ser.write(temp) #write to the serial port
    bytes = ser.readline() #reads in bytes followed by a newline 
    print 'You sent: ' + bytes #print to the console
    break #jump out of loop 
#hit ctr-c to close python window

First thing you need to do before running this code is to change the COM port number to the one that is attached to your FTDI. The COMNUM variable in the first few lines is where you enter your COM port number. If you are running linux, read the comments above for ser.port.

Now, if you want to send data over the serial port, use: 

ser.write(your_data)

your_data can be one byte or multiple bytes.

If you want to receive data over the serial port, use:

your_data = ser.readline() 

The readline() function will read in a series of bytes terminated with a new line character (i.e. typing something then hitting enter on your keyboard). This works great with GPS, because each GPS NMEA sentence is terminated with a newline. For more information on how to use pyserial, look here.

You might realize that there are three communication channels being used:

  1. ser.write - writes or transmitts data out of the serial port
  2. ser.read - reads or receives data from the serial port
  3. print - prints to the console window

Just be aware that 'print' does not mean print out to the serial port, it prints to the console window. 

Notice, we don't define the type of variables (i.e. int i = 0). This is because Python treats all variables like strings, which makes parsing text/data very easy. If you need to make calculations, you will need to type cast your variables as floats. An example of this is in the GPS tracking section below.

Now try to run the script by typing (remember you need to be working out of the directory of the pythonGPS.py file):

python pythonGPS.py

This script will open a port and display the port number, then wait for you to enter a string followed by the enter key. If the loopback was successful, you should see what you sent and the program should end with a Python prompt >>>. 

To close the window after successfully running, hit Ctrl + c.

Congratulations! You have just made yourself a very simple serial terminal program that can transmit and receive data!

Read a GPS and plot position with Python

Now that we know how to run a python script and open a serial port, there are many things you can do to create computer applications that communicate with embedded hardware. In this example, I am going to show you a program that reads GPS data over a serial port, saves the data to a txt file; then the data is read from the txt file, parsed, and plotted on a map. 

There are a few steps that need to be followed in order for this program to work.Install the modules in the order below.

Install modules

Use the same module installation process as above or find an executable package. 

The above process worked for me on my W7 machine, but I had to do some extra steps to get it to work on Ubuntu. Same might be said about Macs. With Ubuntu, you will need to completely clean your system of numpy, then build the source for numpy and matplotlib separately, so that you don't mess up all of the dependencies. Here is the process I used for Ubuntu.

Once you have all of these modules installed without errors, you can download my project from github and run the program with a pre-loaded map and GPS NMEA data to see how it works:

Or you can proceed and create your own map and GPS NMEA data.

Select a map

Any map image will work, all you need to know are the bottom left and top right coordinates of the image. The map I used was a screen shot from Google Earth. I set placemarks at each corner and noted the latitude and longitude of each corner. Be sure to use decimal degrees coordinates.

Then I cropped the image around the two points using gimp. The more accurate you crop the image the more accurate your tracking will be. Save the image as 'map.png' and keep it to the side for now.

Hardware Setup

The hardware for this example includes a FTDI Basic and any NMEA capable GPS unit.

EM-406 GPS connected to a FTDI Basic

For the connections, all you need to do is power the GPS with the FTDI basic (3.3V or 5V and GND), then connect the TX pin of the GPS to the RX pin on the FTDI Basic.

It is probably best to allow the GPS to get a lock by leaving it powered for a few minutes before running the program. If the GPS doesn't have a lock when you run the program, the maps will not be generated and you will see the raw NMEA data streaming in the console window. If you don't have a GPS connected and you try to run the program, you will get out-of-bound errors from the parsing. You can verify your GPS is working correctly by opening a serial terminal program.  

Run the program

Here is the main GPS tracking program file:

Save the python script into a folder and drop your map.png file along side maps.py. Here is what your program directory should look like if you have a GPS connected:

The nmea.txt file will automatically be created if you have your GPS connected. If you don't have a GPS connected and you already have NMEA sentences to be displayed, create a file called 'nmea.txt' and drop the data into the file.

Now open maps.py, we will need to edit some variables, so that your map image will scale correctly. 

Edit these variables specific to the top right and bottom left corners of your map. Don't forget to use decimal degree units!

#adjust these values based on your location and map, lat and long are in decimal degrees
TRX = -105.1621     #top right longitude
TRY = 40.0868       #top right latitude
BLX = -105.2898     #bottom left longitude
BLY = 40.0010       #bottom left latitude

Run the program by typing:

python gpsmap.py

The program starts by getting some information from the user.

You will select to either run the program with a GPS device connected or you can load your own GPS NMEA sentences into a file called nmea.txt. Since you have your GPS connected, you will select your COM port and be presented with two mapping options: a position map...

...or an altitude map.

Once you open the serial port to your GPS, the nmea.txt file will automatically be created and raw GPS NMEA data, specifically GPGGA sentences, will be logged in a private thread. When you make a map selection, the nmea.txt file is copied into a file called temp.txt, which is parsed for latitude and longitude (or altitude). The temp.txt file is created to parse the data so that we don't corrupt or happen to change the main nmea.txt log file. 

The maps are generated in their own windows with options to save, zoom, and hover your mouse over points to get fine grain x,y coordinates. 

Also, the maps don't refresh automatically, so as your GPS logs data, you will need to close the map window and run the map generation commands to get new data. If you close the entire Python program, the logging to nmea.txt halts. 

This program isn't finished by any means. I found myself constantly wanting to add features and fix bugs. I binged on Python for a weekend, simply because there are so many modules to work with: GUI tools, interfacing to the web, etc. It is seriously addicting. If you have any modifications or suggestions, please feel free to leave them in the comments below. Thanks for reading!

EL Wire Quickstart Guide

$
0
0

Let it Glow

When it comes to creating projects that glow, nothing beats EL wire. LEDs are fun and all, but EL wire is what all the hip kids are using. Whether you just want to light up your bicycle for an evening cruise or you're creating an entire light up costume for Burning Man, EL wire is a great solution. In this tutorial, we will show you how to experiment with EL wire without having to worry about how to connect it, how to control it, and how to power it. With the right parts, EL wire can be very easy to implement into any project.

Requirements

If you have purchased the SparkFun EL Wire Starter Kit, you should have everything you need to follow along. If you have purchased just a spool of EL wire, the following is a list of suggested parts to help get you started. With these parts, using EL wire can be simple for those who have no electronics experience at all and for those who are extremely knowledgeable but are looking for a quick and easy solution to using EL wire. Before we go into further detail, let's take a look at what parts we should have:

That might not seem like much, but that's all you need to get started with any EL project.

How it Works

EL wire (short for electroluminescent wire) is particularly useful for many reasons. First, it is flexible, allowing you to sew it into clothing, attach it to moving parts, and bend it into any shape you desire. Second, it comes in many different colors, shapes, and sizes. You can get it in wire form (the most typical shape), tape form, or in panels. (For the sake of this tutorial, I will refer to all of these forms simply as EL wire.) All of these can be cut to any shape or size to achieve the desired effect. Just be sure to reseal the ends that have been cut. Last, EL wire is great because it is cool to the touch, even after being on for hours. Hence why it is often seen in clothing applications. The EL product does not heat up because, rather than heating an element to achieve an optical phenomenon, the glowing in EL comes from sending an electrical current through the material, which is comprised of semiconducting mixtures. The electrons flowing through the material create photons, which create the glowing that we see as a result.

Many people ask, "Can't I just hook up EL wire to a battery?"The answer is, no! In order to operate EL wire properly, you must use AC (alternating current) power. This is similar to the power that comes out of your outlets at home, though outlets provide much more current than needed for EL wire. That's where the inverter comes in. The battery pack included in the EL Starter Kit is not just a battery holder. It houses an inverter as well. This inverter takes the DC (direct current) power produced by the batteries and turns it into AC. If you listen very closely to the inverter battery pack while it's on, you will hear a slight hum, similar to what you would hear if you stand under power lines or close to transformer boxes. (Note: SparkFun does not condone hanging out around high voltage areas). With that, it's important to mention that, although the AC power coming from the inverter is not enough to hurt or kill you, it is enough to give you a good shock, so be careful when handling EL products that are powered. As, I mentioned above, you can cut EL wire to any length or shape, but you must reseal the ends you cut. I recommend using hot glue or epoxy to seal cut wire. If you don't reseal, you could end up getting a good jolt.

How to Use It

Using the EL Wire Starter Kit is about as simple as it gets. Simply plug in the male JST connector from your EL wire into one of the two female JST connectors on the inverter battery pack. Make sure there is a solid connection between the two. Take the battery cover off by sliding in the direction indicated on the pack. Place your batteries in the battery pack inverter, and put the cover back on. Click the button on the case, and your EL wire should illuminate. Press it again for a slow blinking effect, and press it once more for a fast blink. This inverter pack allows you to connect two EL products of your choice at a time. You can mix and match colors as well as shapes. You coul have a red panel with blue wire, green tape with a pink wire, or two yellow and purple wires. The possibilities are endless!

If you need a little more explanation, you can check out our demonstaration video. In it, the two different inverters that SparkFun carries are breifly described, and you can see how each color looks when it’s illuminated.

It’s as simple as that. However, if you are looking for more of a challenge, fear not. EL projects can become very complex, very quickly. You may have noticed that the effects are somewhat limited on the inverter, and both products hooked up behave the same when plugged into it. Let’s say you want one color to blink while the other stays solid. You could purchase another inverter battery pack, or you could get one of the many boards out there that are specifically designed to work with EL products. SparkFun carries two such boards, the EL Sequencer and the EL Escudo Dos. Both of these boards are designed to handle many EL products hooked up to them at once, and there are many different effects you can create with both. If you’re looking for something a little more, check out the Wrapping it Up section.

Wrapping it Up

You should now know everything you need to know to get started with EL wire and the EL Wire Starter Kit. If you have any questions or comments please drop them in the box below. For more information on EL products, how to control them, and project ideas, please check out the following links:

Thanks for checking out our tutorial!

Stepper Motor Quickstart Guide

$
0
0

Stepping Up to the Challenge

There are a handful of motors to choose from, and sometimes it’s unclear as to which one will be best suited for your particular application. In this tutorial, we will discuss one of these motors, the stepper motor, and when it best to choose a stepper motor over the alternatives. We will also discuss how to use this motor with the EasyDriver Stepper Motor Driver board, one of the simplest driver boards around.

Stepper

Requirements

Here is a list of recommended items needed to follow along:

How it Works

Stepper motors vary from regular DC motors in that, rather than just spinning in one direction or another, they can spin in very precise increments. Imagine a motor on an RC airplane. The motor spins very fast in on direction or another. You can vary the speed with the amount of power given to the motor, but you cannot tell the propeller to stop at a specific position. Now imagine a printer. There are lots of moving parts inside a printer, including motors. One such motor acts as the paper feed, spinning rollers that move the piece of paper as ink is being printed on it. This motor needs to be able to move the paper an exact distance to be able to print the next line of text or next line of an image. There is another motor attached to a threaded rod that moves the print head back on forth. Again, that threaded rod needs to be moved an exact amount to print one letter after another. This is where stepper motors come in handy.

Stepper motors can move an exact amount of degrees (or steps) when told to do so. This gives you total control over the motor, allowing you to move it to an exact location and hold that position. It does so by powering coils inside the motor for very short periods of time. The trade off is that you have to power the motor all the time to keep it in the position that you desire. We won’t go into too much detail here, but you can check out this Wikipedia article on stepper motors for all the nitty-gritty information. All you need to know for now is that, to move a stepper motor, you tell it to move a certain number of steps in one direction or the other, and tell it the speed at which to step in that direction.

There are numerous varieties of stepper motors as well as driver boards with which to control them. The methods described here can be used to infer how to use other motors and drivers not mentioned in this tutorial. However, it is always recommended that you consult the datasheets and guides of the motors and drivers specific to the models you have.

How to Use it

Here we will discuss how to assemble, hook up and control your motor with firmware uploaded to the Arduino.

Assembly

The simplest way to use the EasyDriver is to attach headers to it for easy insertion onto a breadboard. Alternatively, you could solder the wires straight to the board. These instructions will assume you are using the breadboard method.

The first step is to solder straight male headers to the EasyDriver. Very few of the actual pins on the EasyDriver will be used in this example. However, soldering headers on all the broken out pins is recommended to give the board more stability when attached to a breadboard. A simple method for this is to break off the desired amount of headers, place them in the breadboard in the appropriate locations, place the EasyDriver on top, and then solder all the connections.

alt text

alt text

alt text

Hook-up

Once you have all the headers soldered on, it’s time to hook up the EasyDriver to your Arduino. Using the picture below, make all the necessary connections.

alt text

Note: The small stepper motor looks different than the one pictured. It should have a 4-pin connector on the end. This will be attached to the 4-pin male header facing upward (see picture #3 in Assembly). Because of the nature of this particular stepper, you can hook up the connector in either orientation, i.e. either the black wire on the left or the yellow wire on the left. It will work either way. If you are using a different motor, consult its documentation to find out which wires should go where.

IMPORTANT: Stepper motors require more power than can be supplied by the Arduino. In this example we will be powering the Uno with a 12V external supply. Notice that the power input (M+) on the EasyDriver is attached to the Vin pin on the Arduino. This will allow you to power both the Arduino and the motor with the same power supply.

Firmware

Once you have everything hooked up correctly, you can upload firmware to the Arduino. The following is some very simple example code to get you up and running. There are numerous examples online, as well as a Stepper library included with the Arduino IDE. Feel free to play around with this code, changing values to see what happens, and feel free to explore other code.

/*************************
Joel Bartlett
SparkFun Electronics
December 27, 2012

This code controls a stepper motor with the 
EasyDriver board. It spins forwards and backwards
***************************/
int dirpin = 2;
int steppin = 3;

void setup() 
{
pinMode(dirpin, OUTPUT);
pinMode(steppin, OUTPUT);
}
void loop()
{

  int i;

  digitalWrite(dirpin, LOW);     // Set the direction.
  delay(100);


  for (i = 0; i<4000; i++)       // Iterate for 4000 microsteps.
  {
    digitalWrite(steppin, LOW);  // This LOW to HIGH change is what creates the
    digitalWrite(steppin, HIGH); // "Rising Edge" so the easydriver knows to when to step.
    delayMicroseconds(500);      // This delay time is close to top speed for this
  }                              // particular motor. Any faster the motor stalls.

  digitalWrite(dirpin, HIGH);    // Change direction.
  delay(100);


  for (i = 0; i<4000; i++)       // Iterate for 4000 microsteps
  {
    digitalWrite(steppin, LOW);  // This LOW to HIGH change is what creates the
    digitalWrite(steppin, HIGH); // "Rising Edge" so the easydriver knows to when to step.
    delayMicroseconds(500);      // This delay time is close to top speed for this
  }                              // particular motor. Any faster the motor stalls.

}

Going further

Now that you’ve figured out how to operate your stepper motor at the simplest level, it’s time to take it to the next level. There is a vast amount of information on the web regarding the Easy Driver and stepper motors in general. The best place to look next would be the EasyDriver website. There is also an great tutoral on the bildr website. Another great resource is the EasyDriver Schematic. If you’re curious as to what the other pins on the EasyDriver do, the schematic will give you some insight. Lastly, you can check out one of my projects involving stepper motors, the Arduija. In it, I use stepper motors controlled by EasyDrivers to create an X-Y gantry that moves a Ouija board automatically.

You should be well on your way to adding stepper motors to your next project. If you have any questions, comments or just want to show off your project, drop us a line in the comments below. Happy hacking!

Mono Audio Amplifier Quickstart Guide

$
0
0

This tiny audio amplifier is based on the Texas Instruments TPA2005D1. It can drive an 8-Ohm speaker at up to 1.4 Watts; it won't shake a stadium, but it will provide plenty of volume for your audio projects.

Quickstart

  • Connect your line-level audio input to the IN + and - header.
  • Connect your speaker to the OUT + and - header.
  • Connect 2.5V to 5.5V to the PWR + and - header. (Don't connect anything to the S (shutdown) pin yet.)

Send some audio to the input, and you should hear it on the speaker! If the sound is not loud enough, if you hear buzzing, or if you'd like to add a volume control, read on.

How it works

Traditional audio amplifiers use power transistors to multiply an analog input by a certain gain to produce an analog output. This produces great sound, but the transistors must operate in the intermediate region between on and off. Transistors operate most efficiently when they're fully on or off, and waste a lot of energy as heat when they're run in between.

The class-D amplifier is radically different. At any moment its output transistors are either fully on or fully off, which is very efficient. But this means that the output isn't true audio, it's a digital PWM-like waveform which is mostly on (VCC) for high output values, and mostly off (GND) for low output values.

This PWM signal is clocked at 250kHz, which is much higher than the audio frequencies being encoded (< 20kHz). Because speakers are mechanical devices that can only respond to audio frequencies, the PWM signal is effectively filtered back into the original audio frequencies by the speaker coil itself. All you hear is the music!

Check out the TPA2005D1 datasheet if you'd like to know more about this amplifier.

To use the amplifier

Connect your input source to the IN + and - header. Because the inputs are differential, it technically doesn't matter which direction you connect them, but if one of your inputs is ground or shield, connect that line to the - terminal. (See the Tips below if you're having problems with hum).

Connect your speaker to the OUT + and - header. If you're using one speaker the polarity doesn't matter, but if you'll be using multiple speakers, ensure that you wire them all the same way to avoid phase problems. The speaker can be 4 or 8 Ohms. The maximum output of the amplifier is 1.4 Watts into 8 Ohms. You can drive smaller-wattage speakers with this amplifier, but you should be careful not to turn up the volume too high to avoid damaging the speaker. You can also drive speakers larger than 1.4W at reduced volume. In general, larger speakers will sound much better than smaller speakers; we've had great luck with old automotive speakers.

Connect a power source to the + and - pins. The power source can be from 2.5V to 5.5V, and should be able to source at least 280 milliamps if you want maximum volume. The red LED will illuminate when the board is powered up.

Apply an audio signal to the input, and you should be able to hear it on the speaker. To change the volume, either change the volume of the signal at its source, or add a volume-control potentiometer to the board (instructions below).

Adding a volume control knob

If you wish, you can easily add a 10K volume control potentiometer to this board. The volume control will let you control the volume by reducing the input signal from 100% to 0%. Note that this will not make the amplifier any louder - if you'd like to do that, see changing the gain resistors below. Here's how to add a volume control potentiometer:

Remove the solder from jumper SJ1. This is the small blob of solder within the white brackets on the bottom right of the board. The easiest way to do this is to apply solder wick to the jumper, and heat it with your soldering iron. When you're done, ensure that the two sides are electrically separated from each other.

Now, connect your 10K potentiometer to the three pads on the lower right of the board. The bottom of the board has silkscreen showing the proper connections. You can solder a trimpot with 0.1"-spacing on the pins (such as COM-09806) directly to the board, or you can use wires to connect the board to a larger potentiometer in a chassis, etc.

Note: Potentiometers come in two styles: "linear taper"and "audio (or logarithmic) taper". Audio taper potentiometers have a logarithmic bias that give a more natural feel in audio volume control applications like this one, but linear taper will also work just fine.

How to use the shutdown pin

The SDN* input can be used to turn off the amplifier to save power when it's not being used. When SDN* is disconnected, or connected to a high logic signal (> 2V), the amplifier will function normally. When the SDN* pin is connected to ground or a low logic signal (< 0.8V), the amplifier and LED will turn off. You can use this feature to save power in battery-operated projects.

Changing the gain resistors

The amplifier chip uses two fixed resistors to set the gain, which is how much the input signal will be amplified. On this board, we're using 150K resistors as recommended by the datasheet, for a gain of 2. If you would like the output to be louder, you can install smaller resistors.

The gain equation for this amplifier is 2 * (150K / R). So if you use 100K resistors the gain would be 3, for 50K resistors the gain would be 6, etc. The datasheet states that the smallest value you should use is 15K for a gain of 20, but we've gone down to 3K (gain = 100) with fair results.

The amplifier board has two positions to add your own through-hole resistors. These are within the white rectangles on the top of the board. You do not need to remove the existing surface-mount resistors, just put your through-hole resistors over the top of them. (Leaving the SMD resistors in parallel with the new resistors will slightly reduce the total resistor value, but this is generally not a problem).

For best results, the two gain resistors should be as closely matched as possible. If you have a bag of identical resistors, you might measure them all with a multimeter and pick the two that have the closest resistance.

Tips

The amplifier's output is only designed to be connected to something with a coil (a speaker or magnetic transducer). Since the output is not a true analog signal, you shouldn't expect to use this board as a preamplifier, etc.

The differential inputs of this board are safe to connect directly to floating-ground audio signals such as from the MP3 Shield and MP3 Trigger.

If your audio source and amplifier have different AC power supplies (such as audio coming from a desktop computer), you may hear a loud hum in the output. To fix this, connect a jumper wire between the - side of the audio input and the power supply ground (PWR - header).

Because the amplifier outputs a 250Khz PWM-like signal, it could potentially radiate interference to nearby sensitive circuitry. For this reason, keep the wires between the amplifier and speaker as short as possible.

Questions?

If you have any questions or problems, let us know at techsupport@sparkfun.com and we'll do our best to help you out. We'd also like to hear about the cool projects you're building with our parts!

Have fun!
- Your friends at SparkFun.

Flexiforce Pressure Sensor (25lbs) Quick Start Guide

$
0
0

Introduction

This is a quick how-to explaining everything you need to get started using your Flexiforce Pressure Sensor.  This example uses the 25lb version, but the concepts learned apply to all the Flex sensors.

Flexiforce

Requirements

Necessary hardware to follow this guide:

You'll also need the Arduino IDE for programming.

Hardware

The Flexiforce Pressure Sensor is essentially a variable resistor. When no pressure is applied, the resistance between the two outer leads is incredibly large, probably greater than 10 Mega Ohms (more than my meter can measure). When pressure is applied, the resistance measured between the outer leads lowers until you've reached the max pressure it's intended to measure. In this case that's about 25 lbs of pressure, and the current Flexiforce Pressure sensor I'm using measures about 50K Ohms when given that max amount of pressure.

You can test the range of your sensor using a multimeter. Just attach the two outer leads to the multimeter and set the meter to measure resistance. Then squeeze the sensor and watch the resistance value change.

Now, let's read values with an Arduino. To do this, we create a voltage divider circuit with the Flexiforce sensor and an extra resistor. I picked 1M Ohm in this example because it's about in the middle of the Flexiforce sensor's dynamic range. Many other similar values could work as well.

Connect 5V to one side of the voltage divider, and GND to the other. In the middle, where the Flexiforce sensor and the resistor connect, connect one of the analog-in pins of the Arduino with a jumper wire. In this case I used pin A0. Here is a Fritzing diagram of the setup:

alt text

Fritzing Wiring Diagram

*Note*: The sensor in the image doesn't look exactly the same as the Flexiforce sensor, but very close. The actual Flexiforce sensor has a larger surface area.

Software

Now that you have your circuit wired and ready, it's time to write some very basic Arduino code.  This code is almost exactly the same as Arduino's standard AnalogReadSerial example. Let's take a look to see what it's doing:

 
// Flexiforce quick start example// Reads A0 every 100ms and sends voltage value over serialvoidsetup() 
{
  // Start serial at 9600 baud  Serial.begin(9600); 
}

voidloop() 
{
  // Read the input on analog pin 0:  int sensorValue = analogRead(A0);
  
  // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):  float voltage = sensorValue * (5.0 / 1023.0);
  
  // Print out the value you read:  Serial.println(voltage);
  
  // Wait 100 milliseconds  delay(100);
}

The code is simply running in a small infinite loop every 100ms, or 10 times a second. In each pass through the loop, it measures the voltage on pin A0 and returns a corresponding value between 0 and 1023. 0 represents ground in this case and 1023 indicates A0 is sitting at 5 Volts. For other numbers in between, we can figure out the voltage by multiplying the measured number by the fraction, 5.0 / 1023.0. We then spit this value back over the Serial port, we can watch the values change in real time.

Go ahead and try. Make sure you have the hardware connected correctly. Program the Arduino, open up the Arduino Serial Monitor (make sure it's using 9600 baud), and watch the voltage values change as you press and release the Flexiforce Pressure Sensor.

Conclusion

Now you know how to use the Flexiforce Pressure Sensor. Believe it or not, there are many different analog sensors where you can use what you learned here and collect data the exact same way. Now it's all up to you to use these types of products however you imagine. If you have any other questions or comments, please drop them in the box below. Enjoy!

Viewing all 1123 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>