Saturday, September 13, 2014

Building a Color Sensor using the Adafruit TCS34725 and an ATMega32A Microprocressor

This project uses the Adafruit TCS34725 RGB Color Sensor and an ATMega32A microprocessor to collect and display color data in a WPF application.

The TCS34725 RGB color sensor is a neat little sensor. The sensor itself uses a photo-diode array with red, green and blue filters to measure color temperatures in Kelvin. The Adafruit library takes care of communications with the sensor, and converts the color temperatures to familiar RGB values. The Adafruit breakout for the sensor also includes a white led to illuminate objects so you can use the sensor for reflected light from colored objects when the light is on, or turn the light off and use the sensor to detect the color of light emitted from an external source (such as an RGB led). I use a push button to make it easy to toggle the led on or off.

Parts List

ATMega32A-PU   ($3.15)
USB to TTL Serial cable ($9.95)
TCS34725 RGB Color Sensor ($7.95)
A tactile switch button ($2.50 for 10 pack)
A 10k Resistor ($0.25)
Perma-Proto half-sized breadboard PCB ($4.50) (optional)

Estimated Cost ~$26

Additional Hardware Tools Need

An ISP Programmer or an Arduino Board to use as an ISP Programmer
A breadboard and some wires
A soldering iron (optional)
A 10pF capacitor if using the Arduino as an ISP Programmer


Arduino IDE 
Visual Studio Express 2010 (with C#)
ATMega32 board and pin files
Adafruit_TCS34725 library
Color Sensor sketch for ATMega32
Color Sensor WPF Application

Step 1: Environment Setup

  1. Download the Arduino IDE and install it (if you don't have it already)
  2. Install the boards and pins files for the ATMega32 to the Arduino IDE
  • Download the ATMega32 board and pin files
  • Create a folder named mega32 in the directory:
           C:\Program Files (x86)\Arduino\hardware\arduino\variants
  • Copy the arduino_pins.h file to the folder you created:
           C:\Program Files (x86)\Arduino\hardware\arduino\variants\mega32
  • Copy the text from the boards.txt file and past it into the boards.txt located at:
           C:\Program Files (x86)\Arduino\hardware\arduino\boards.txt
  • Open the Arduino IDE. You should now see the ATMega32 boards under the
    Tools -> Board  menu.  Select ATMega32 - 1mhz

Step 2: Program the ATMega32 with the color sensor sketch

If using an arduino as an ISP:

  • Upload the ArduinoISP sketch from  File->Examples -> ArduinoISP in the Arduino IDE.
  • Set up the circuit for to use the Arduino as an ISP programmer by making the following connections:

Arduino Mega/ Uno Pins to ATMEGA32A Pins
MISO pin 50/ pin 12->pin 7 MISO
MOSI pin 51/ pin 11->pin 6 MOSI
CLK pin 52/ pin 13->pin 8 SCK
SS pin 53/ pin 10->pin 9 RESET
5V->pin 10 VCC
GND->pin 11 GND
RESET to Capacitor to->GND

  • Under Tools->Programmer select the "Arduino as ISP" option.
If you are using another flash programmer, select the appropriate option for your device.

Next, upload the Color Sensor stetch to the ATMega32:
  1. Download and Install the Adafruit_TCS34725 library to your Arduino IDE.
  2. Download the Color Sensor Sketch and open it in the Arduino IDE. 
  3. Select "ATMega32 - 1mhz" as your board under Tools -> Board. 
  4. Make sure the Serial Port is selected under the Tools menu.
  5. Press Ctrl + Shift + U to upload the code using a programmer. 

If everything worked you should see the message "avrdude done. Thank you.".

Step 3: Setup the Color Sensor Circuit

Now that the ATMega32 is programmed for the Color Sensor, lets set up the circuit and test it out. The diagram below shows the circuit connects for the sensor. The power is supplied by the USB to TTL cable through the USB port. The circuit connections needed are shown in the diagram below.
Color Sensor Circuit Connections

Step 4: Test the Circuit with the Color Sensor WPF application

Download the Color Sensor WPF Application.
Open the solution file in Visual Studio 2010 Express and compile it. Here is the link to download and install Visual Studio Express 2010 (with C#) if you do not have it.
Plug in the USB to TTL Serial cable to your computer.
The led light on the color sensor will come on at this time. If your circuit is correct, you should be able to turn it off by pressing the button.
Windows should automatically recognize the serial connection and assign it to a COM port. You can see which COM port it is on either by looking in  the Device Manager under Ports (COM and LPT) or in the Arduino IDE the COM port will show up as a selection under Tools->Serial Port.

If everything worked so far, it's time to run the Color Sensor application. You can run the application in debug mode by pressing F5 in Visual Studio if you still have the solution open.  It should look something like picture below:

ColorSensor-WPF application running in Debug Mode

Select the correct COM port for your USB to Serial TTL cable and press the Start button to begin receiving color data from the color sensor.
After you press the Start button, you will see the Current Color and Gamma Color change based on the colors detected by the sensor!

Step 5; Experiment with the the Color Sensor using different colored objects

If you want to see the color of an object that does not emit light such as a notebook then press the button on the sensor a few times until the led light ON.
With the light on, try holding different colored objects up to the sensor so that the led light is reflected back onto the adjacent sensor array.
Notice the color show in Current Color compared to the actual object color? The color sensor is better at detecting some colors than others..

It is pretty good at detecting that a color is blue.. Here is the result when I held a blue Nivea lotion bottle directly up to the sensor. I set the Compare to Color Value to pure blue for an reference color. The Gamma Color Value doesn't seem to be closer for these purposes. It seems much darker.

The Current Color is the color detected when a blue object was held up to the sensor.

Now I'd like to try a few other object colors. here is the screen shot from the output from a red ball.
The Current Color is from a Red Ball held up to the Sensor.
Red and Blue are not perfect, but they are at least in the right range, lets try green.Green is not too bad but not perfect either. 

So what about mixed colors like yellow?  Here is what it looks like when I hold a yellow object next to the sensor:

The yellow object appears more olive green than yellow. It seems to detect more green from the yellow, but not enough red to show the yellow. Hopefully I can find a way to adjust the colors so they are closer to those of the actual object. The gamma corrected color doesn't seem like it's going to help here either, it still appears too dark.

Other References

The AMS Light Sensors product Website - Look under Technical Documentation. There are several documents that explain the science in measuring and converting color temperature to RGB values. If you dig into the Adafruit library, you will see the formula's there come from this documentation.

TCS34725 color sensor data sheet
TAOS Inc (now AMS)

Sunday, August 24, 2014

Setting up the Toolchain for Atmel AVR programming in Windows

The basic setup for an open source toolchain will get you pretty far in programming Atmel AVR's that are supported by avr-gcc. If you want to program these AVR's directly using standard c code, you'll need a toolchain, plus some hardware.  Here are my notes for setting this up on a Windows 8 machine.

Hardware Needed:

  1. ATMega32A - PU (the PU package is breadboard friendly)
  2. An ISP / USB Flash Programmer -
    This is a USB device that allows you to send compiled hex files down from your computer to the chip. The device uses the SPI interface and  reset on the chip to load code onto the chip. I've been using my Arduino Mega for this.
  3. Some basic hardware: A Breadboard, an LED, and some wires for testing.

Software Needed:

  1. Notepad++  (You could also use Programmers Notepad that is included with the WinAVR suite or another IDE to edit and write your code).
  2. WinAVR - This is an open source suite of compiler tools that includes the compiler and AVRDUDE uploader software in one great package
    •  avr-gcc - this a compiler you can use to compile c  and c++ code and turn it into a hex file that can be run on an ATmel AVR 
    • AVRDUDE - This is the software tool that understands how to make your flash programmer upload your hex compiled code to your AVR chip.
  3. make file - these are text files that allow you to run all the tools in one easy step from from compiling your c code with avr-gcc to uploading it with AVRDUDE
  4. Code to upload and test with.

Step 1: Install WinAVR

  1. Download WinAVR and install it on your computer.
    You can download WinAVR from sourceforge by clicking here.
  2. Download Notepad++ and install it on your computer (or use another editor).
    You can download Notepad++ here

Step 2:  The Makefile

A make file is sort of like a script (or batch file) that can help you compile your code and then do other stuff too. In this case, it's going to compile your code and if your circuit connections are good, it's going to upload your code to the AVR chip! Sweet right!?! The easiest way to get started with make files is to start with one that already does most of what you want it and customize it for your needs.
Click here to download a Makefile and blink.c code to test with.

The make file contains only a few items that need to be changed. These are items specific to the type of programmer being used, the target avr chip, and the source code being compiled and uploaded.

Target AVR Flags:

MCU = atmega32    
F_CPU = 1000000
BAUD = 9600

MCU :   This tells avr-gcc what target to compile the code for.  In this case the target is an atmega32. To find out what other targets are supported just go to the command prompt and type:
  avr-gcc --target-help
F_CPU :   This tells avr-gcc the clock frequency in Hertz for the target AVR. This needs to be correct for anything timing related to work properly. Note: this does not set the clock frequency! It just tells avr-gcc what the frequency is. The specifics of the clock operations can be found by searching for "System Clock and Clock Options" in the ATMega32 Datasheet. It may be a bit daunting, but basically it tells you that the default clock source is set to 1 MHz.
BAUD : This is the baud rate used for serial communications between the avr and your computer. This just tells the avr what speed you want to talk at. The avr may support higher baud rates that are documented in the datasheet. 9600 is a safe default.

Source Code specifiers:

MAIN = blink.c
LOCAL_SOURCE = blink.h
EXTRA_SOURCE_DIR = ..\..\lib
EXTRA_SOURCE_FILES = myotherfile.c

MAIN:  The source file that contains your main function.
LOCAL_SOURCE:               Additional code files in the same directory as your main file.
EXTRA_SOURCE_DIR :      Specify another directory to look for source files.
EXTRA_SOURCE_FILES:   Specify additional source files to include.

Every Make file usually has some way of specifying these, although it often has different variables than the ones above. Check out the one make file template included with WinAVR to see one that is very different.

 Programmer Flags:

PROGRAMMER_ARGS = -v -v -cstk500v1 -P\\.\COM4 -b19200

PROGRAMMER_TYPE :    This is the name that tells avrdude what programmer you are using. To find out what programmer options are supported in avrdude go to the command prompt and type:
avrdude -c ?
PROGRAMMER_ARGS :   These are all the other arguments that will be passed to avrdude. Depending on the type of programmer you use. To use the arduino as an ISP, I need to specify that the Arduino is on COM4, and that the ISP programmer code uses a baud rate of 19200. Also stk500v1 tells it to use the Atmel STK 500 version 1 and -v -v tells it to give verbose output.

STEP 3: Circuit Setup - Arduino as an ISP programmer

The circuit setup is the same as it was to program the ATTIN84A except that the pins are different on the ATMega32A.

Arduino Mega/ Uno Pins to ATMEGA32A Pins
MISO pin 50/ pin 12->pin 7 MISO
MOSI pin 51/ pin 11->pin 6 MOSI
CLK pin 52/ pin 13->pin 8 SCK
SS pin 53/ pin 10->pin 9 RESET
5V->pin 10 VCC
GND->pin 11 GND
RESET to Capacitor to->GND

STEP 4:  Program the Arduino as an ISP programmer

To turn the Arduino Mega into an AVR ISP you need to upload the  ArduinoISP sketch to your Arduino board.
  1. Using the USB cable, connect your Arduino Mega 2560 or Arduino Uno to your computer.
  2. Open the the Arduino IDE. 
  3. Under Tools -> Boards select the "Arduino Mega 2560" (or select "Arduino Uno" if you are using that instead) as the board.
  4. Under Tools -> Programmer select "AVR ISP"
  5. Select File -> Examples -> ArduinoISP to open the Arduino ISP sketch. 
  6. Compile the sketch and upload it to your Arduino Board. 
   Your Arduino is now ready to use as an in system programmer!

STEP 5: Run the Makefile 

Now we are ready to test it out. 
  1. Make sure the COM port in the make file  PROGRAMMER_ARGS matches the one the Arduino is connected to. (It is currently set to COM4 in the make file).
  2. Once the COM port is correct, go to the command line in the directory where the Makefile and blink.c are extracted.  On the command line type:
    make flash
   If it works you should see a lot of output with no errors. At the end it should say:
   avrdude done.  Thank you.
If you get an error, check your circuit and make sure the connections are correct. Also verify the COM port is correct,  and verify the baud rate matches the ArduinoISP sketch.

STEP 6: Test the blink code on the ATMega32 with an LED

If everything else worked above, connect an LED from Pin 1 (PB0) to ground.  And it blinks!


Saturday, August 23, 2014

Bit Twiddling Reference for AVR programmers

If you do any AVR programming in c or c++, you'll very likely need these operations. As often as I've seen them, I still sometimes need to look these up if I haven't used them in a while. So here they are...

Assume that the variable myByte is a 8 bit variable defined as the following in c code:
                                                                  byte myByte = 0x00;

The above line of code sets all 8 bits (0-7) to 0, turning them all OFF using the hex notation.

Set bit  i (ON/1):                          myByte |= (1 << );

Clear bit  (OFF/0):                    myByte &= ~(1 << );

Toggle bit                                myByte ^= (1 << );

Saturday, July 26, 2014

Use an Arduino Mega 2560 to program an ATTINY84A

This is a hello world AVR programming project. A simple way to get started programming an inexpensive AVR chip for anyone who has an Arduino board. I am going to use an Arduino Mega 2560 as an ISP AVR programmer but you can also do this with an Arduino UNO or any board with a SPI interface if you know how. 

If you have been working with some developer boards like the Arduino UNO or the Arduino Mega 2560, and you are comfortable soldering your own projects, then you might have realized that the chips alone usually cost from $1-$3 and take up a lot less space than the breakout boards do.  The good news is, you can easily get started programming these chips using the developer board that you have on hand! 

For this example, I am going to use my Arduino Mega 2560 as an ISP AVR programmer to program an  ATTINY84A-PU chip to do a simple LED blink. There are other ways to program this chip, but if you happen to already have an Arduino board on hand and don't want to spend the extra money to buy a programmer, this is a quick and easy way to get started.  

Parts List: 

  1. 10mm Ultra-High Brightness Blue LED - any LED will work
  2. An Arduino Mega 2560  or UNO 
  3. A 10uF capacitor
  4. An ATTINY84A-PU  ($1.41)
  5. Small Breadboard
  6. Connection Wires

The first thing you need to do is be able to program your chip using the Arduino Mega. To do that with the Arduino IDE you will need to install the Tiny bootloader and supporting libraries into the Arduino IDE. Then you will need to set up the circuit for the programmer, upload a blink sketch to the chip, and finally, setup the chip circuit to work with the blink circuit.

Using the Arduino Mega as an AVR programmer

Step 1: Prepare the Arduino IDE environment to program the ATTINY84A 

You need to be able to compile code into a hex file to load onto the ATTINY84A and upload that code from the Arduino IDE but the functionality to do that requires some additional software components that are not included by default.

  1. Click here to download the "Tiny" archive 
  2. Create a new directory named tiny under your ..\Arduino\hardware directory.
    For newer versions of the Arduino IDE, this may be located in:
         "C:\Program Files (x86)\Arduino\hardware"
  3. Copy and paste the contents of the tiny/avr directory of the archive to the ..\Arduino\hardware\tiny directory you created.
  4. In the  ..\Arduino\hardware\tiny directory, rename the Prospective Boards.txt file to boards.txt
  5. Open the Arduino IDE. You should see the ATTINY84 under the Tools->Boards menu.

Step 2: Program the Arduino Mega 2560 to be an AVR ISP

To turn the Arduino Mega into an AVR ISP you need to upload the  ArduinoISP sketch to your Arduino board.
  1. Using the USB cable, connect your Arduino Mega 2560 or Arduino Uno to your computer.
  2. Open the the Arduino IDE. 
  3. Under Tools -> Boards select the "Arduino Mega 2560" (or select "Arduino Uno" if you are using that instead) as the board.
  4. Under Tools -> Programmer select "AVR ISP"
  5. Select File -> Examples -> ArduinoISP to open the Arduino ISP sketch. 
  6. Compile the sketch and upload it to your Arduino Board. 
   Your Arduino is now ready to use as an in system programmer!

 Step 3: Hardware Setup to use the Arduino ISP (for the ATtiny84)

Next we need to make the connections between the Arduino Mega (or Uno) and your ATTINY84A chip.
The Arduino Mega has a hardware SPI interface on pins 50 - 53 that can be used to program other chips like the ATTINY84A as shown in the picture below. (If you are using the Uno, pins 50, 51, 52, and 53 on the Mega should be mapped to pins 12, 11, 13, and 10 on the Uno). 

Arduino Mega 2560 Hardware SPI Pins
(note: we also use pin 53 - the SS pin to reset to ATtiny84)

We need to connect the SPI pins from our Arduino to the SPI pins on the ATTINY84A. I am using the ATTINY84A-PU because the PU extension chips are breadboard friendly. The pins needed for this on the ATTINY84A are shown below.

(note: the RESET Pin 4 will also be needed)

Curcuit setup for the ISP AVR programmer

Unplug the Arduino Board and make the following connections:

Arduino Mega/ Uno Pins to  ATTINY84A Pins
MISO pin 50/ pin 12 ->pin 8
MOSI pin 51/ pin 11 ->pin 7
CLK pin 52/ pin 13 ->pin 9
SS pin 53/ pin 10 ->pin 4
5V ->pin 1 VCC
GND ->pin 14 GND
RESET to Capacitor to ->GND

Step 4: Use the AruinoAVR ISP to program the ATTINY84A

  1. Plug in the USB connection for Arduino board to your computer.
  2. Open the Arduino IDE.
  3. Open the Arduino Blink sketch by selecting
              File -> Examples -> Basics -> Blink.
  4. Change the led pin in the blink sketch by changing
                       "int led = 13;" to "int led = 1;"
  5. Select the ATtiny84 @ 8 MHz Internal Oscillator by selecting
              Tools -> Boards ->  ATtiny84 @ 8 MHz Internal Oscillator

    (Caution: Do not select the External oscillator unless you have added an external oscillator; this can cause issues if selected by mistake).
  6. Choose the Arduino as an ISP programmer by selecting
               Tools-> Programmer-> "Arduino as ISP"
  7. Upload the sketch to the chip by selecting
               File-> "Upload Using Programmer" or pressing Ctrl +Shift + U.

Step 5: ATTINY84A-PU LED Blink Hardware Setup

This is the easiest part.. connect the LED o Pin 3 of the ATtiny84, connect the power and ground pins and you will see the LED blink on and off slowly.

Make the connections:

   ATtiny84 Vcc Pin 1     -> 3.5V to 5V source voltage
   ATtiny84 GND Pin 14 -> Ground
   ATtiny84 Pin 3 /PB1     -> LED +
                            LED-  -> Ground

I used a Lipo battery I had to power it but you could also power it from the Arduino 5V, or another power source you might have.

Here is another useful link with more details for doing this with the UNO.
Using the Arduino Uno to program ATTINY84-20PU

Sunday, June 29, 2014

LPD8806 RGB Light Strips - Using an Arduino Mega to count the pixels

The goal of this project is to count the number of LED pixels on a  LPD8806 light strip using SPI MISO and the DO (Data Out) pin at the end of the strip. I used the hardware SPI pins on the Arduino Mega 2560 because it is faster and more reliable than a bit banged software SPI. The code will send data to the light strip increasing the number of pixels on the strip each time until it reaches a maximum number of pixels specified in the code, or until data is found in the Arduino's SPI MISO buffer.  I used 100 as the maximum but this could be changed to any number.

This technique can be used to connect a strip of any length and dynamically determine the number of LED pixels on the strip at start up. This allows for trading out light strips of different lengths without changing the code, as long as the maximum number of LED pixels set in the code is greater than the number of the longest light strip that might be used.

The disadvantage of this technique is that you need a physical connection to the end of the light strip. It would be really cool if they added a 5th connection to the strip that was pass through. Then the DO at the end of the strip could be connected to the pass through line and all the connections here could be at the beginning of the strip.

Click Here to get the Code

LPD8806 RGB Light Strips and SPI 

The LDP8806 light strips are used as a slave device on a SPI bus to transfer data to each pixel in the strip.The hardware SPI (Serial Peripheral Interface) available on the Arduino Mega 2560 is on Pins 50, 51, and 52. The Arduino is the master device, and the light strip is the slave device.

As shown in the image below, pin 52 is the CLK (Clock), pin 51 is the MOSI (Master Out Slave In), and pin 50 is the MISO (Master In Slave Out). The MOSI and CLK pins are used to send data to the light strip. The MISO pin will be used to receive data from the light strip.

Arduino Mega 2560 Hardware SPI Pins

The light strip has 4 connections at the beginning of the strip labeled GND, DI, CI, and +5V and 4 connections at the end of the strip labeled GND, DO, CO and +5V. The connections at the beginning of the strip are used to send data to the light strip and power the light strip. The DO pin at the end of the strip is used to receive data back from the strip.

LPD8806 RGB Light Strip Pins
Light Strip Data
At the beginning of the light strip, the DI and CI pins are the Data In and Clock In pins. The DI pin is connected to the Arduino MOSI (pin 51) and the CI pin is connected to the Arduino CLK (pin 52).
The DO pin at the end of the strip is connected to the MISO (pin 50) on the Arduino. If this pin is not connected, you will never receive data back from the strip!

Powering the Light Strips
The light strip requires an external 5 volt power supply. The Arduino cannot supply enough power to run these strips.

Step 1: Making the Hardware Connections

Parts Needed:

  1. Arduino Mega 2560 ($16)
  2. LPD8806 RGB LED Light Strip ($30)
  3. Power Supply to supply 5 Volts to light strip - I used an old PC power supply but this one will also work, Power Supply + 5 volts ($8) 
  4. You may also need connectors to connect the power supply to your bread board depending on your setup
  5. A bread board 
  6. Some connection wires
  7. A Soldering Iron  (to make connections to the light strip)
  8. A voltage meter to measure supply voltages and ensure they are at or around 5 volts. 

Here is the diagram of the circuit I used: 
Circuit Diagram: LPD8806 RGB LED Light Strip and Arduino Mega


Connections at the START side of the Light Strip
  1. Identify the START side of the light strip, this is the side with the labels DI, and CI on the two center connection pads. Connect the GND on START side of the light strip to the power source GND on the bread board. 
  2. Connect the +5V pad on the START side of light strip to the power source +5V on the bread board.
  3. Connect the DI pad on the START side of the light strip to the Arduino Mega's MOSI (pin 51). 
  4. Connect the CI pad on the START side of the light strip to the Arduino Mega's CLK (pin 52). 

Connections at the END side of the Light Strip
  1. Connect the DO pad on the END side of the light strip to the Arduino Mega's MISO (pin 50).
  2. Optionally, you can also connect the GND and +5V on the END side of the light strip to the power source GND and +5V.

Additional Arduino Connections
  1. Connect the Arduino Mega GND pin to the GND from the power source. 
  2. Plug in the USB connection from the Arduino to your Computer.
Make sure the power to your power source is turned on. 

Step 2: Loading and Running the code

  1. Click here to download the sketch for the Arduino
  2. Open the Sketch in the Arduino IDE. 
  3. Select the Arduino Mega 2560 under Tools->Boards in the Arduino IDE
  4. Make sure the Port for the Arduino is selected under Serial Ports
  5. Change  the maxLEDs value in the code to your preferred maximum. This should be a number larger than the largest number of LED pixels any of your LED strips might have.
  6. Compile and Upload the sketch. The code will start running immediately and the LED's on the light strip should turn blue one by one. 
  7. Open the the Serial Monitor from the Arduino IDE to see the output from the code. If everything is wired correctly, you should see the following line at the end of the output with the correct number of pixels for your light strip:
             "Found 64 LED pixels in the strip.
  8. If the MISO/DO connection is not connected, then the following line will be seen at the end of the output:
    "No Data received after testing the maximum number of LEDs 100 Is the DO on the light strip connected to the MISO pin?"

Sunday, May 18, 2014

Teensy 3.1 Accelerometer - Control a Game Object in Unity

Getting the accelerometer data from the Teensy is nice, but the WPF application with some lines on the screen was sort of boring. I wanted to do something more fun with the Teensy 3.1 Accelerometer - use it as a game controller!  So this project is all about using the Teensy 3.1 Accelerometer to control an airplane on the screen using the Unity game development suite.

Hardware Setup

  1. Follow the instructions to build the Teensy 3.1 Accelerometer. This will be used as the game controller through a  USB serial connection.
  2. Note: the Unity game expects the Accelerometer's x, y, and z axis' to be oriented with the Y-axis arrow pointing to the right of the user and the X-axis arrow pointing toward the user when the circuit is in use. 

Software Setup

  1. Download and install the Unity game development suite. (this takes a while, it's a big download)

Now lets take a get the Unity project working.

Step 1 - Download the Unity Plane Game project.

  1. Download the file and extract it to a UnityPlaneGame directory. 
  2. Create an Assets directory under the UnityPlaneGame directory that was just created on your local drive.
  3. Download everything in the UnityPlaneGame/Assets directory of the repository and to your Assets directory. 
  4. Extract the .7z compressed files to sub directories of the Assets directory that match the compressed file names. You will need 7-zip to extract the files. You can download 7-zip here.
  5. Copy the scripts directory and other files directly to the root of your Assets directory. Your Assets directory file structure should look as shown below. 

Step 2 - Open the Unity Project.

  1. Open the Unity Game development suite. 
  2. From the "File" menu, select "Open Project", then choose "Open Other" at the bottom left corner and browse to the UnityPlaneGame directory. Then click the "Open" button.
  3. The project should open and look something like the image below.

  4. Now Choose "Build and Run" from the "File" Menu to make sure the project will build. If not, verify the above steps.

Step 3 - Change the COM port to match your Teensy 3.1 Accelerometer

  1. From the Project window in Unity, navigate to the scripts directory and open the PlaneAnimator.cs script by double clicking on the file. The file will open with MonoDevelop. 
  2. In the script, change the COMPORT string from "COM6" to the COM port that your Teensy 3.1 Accelerometer is on and Save your changes.

Step 4 - Run the Game

  1. At this point, make sure your Teensy Accelerometer is plugged in. (The USB cable). The game is programmed to open the serial port only once on start up, so it will not work if you plug it in after the game is already running.
  2. Return the the Unity project window. 
  3. From the File menu, select Build and Run. A window will open with the Unity logo in it, and then the game scene will appear with the plane visible on the screen. Try using the Teensy accelerometer to control the plane. Tilting the accelerometer left and right should make the plane move left and right. Also try tilting it back with the front side higher than the backside. That should make the plane climb on the screen. Tilt it in the opposite direction to make the plane dive. See if you can find the buildings and fly through them! There are no collisions in the game so you can fly through anything! 

Sunday, May 11, 2014

Teensy 3.1 Accelerometer - Controlling WPF UI Objects

Now that I can get the data from the Accelerometer, it would be nice to do something with the data. This project demonstrates how to use the serial data from the  Teensy 3.1 Accelerometer project to update objects on a screen in a simple C# WPF (Windows Presentation Foundation) application.  The data received from the accelerometer is used to change the size of lines mapped to the X, Y, and Z axis values of the accelerometer.

1. Complete the steps described to hook and program the Teensy 3.1 Accelerometer

Software Setup

3.  Get the WPF application code. Download the repository as a zip file and extract it. 

Set the COM Port and Build

4. Navigate to the  ADXL335SerialApp directory and open the ADXL335SerialApp.sln solution file with Visual Studio.
5. Open the Window1.xaml.cs file and change the COMPORT to the one used by the Teensy accelerometer.

6. Save the file and build the solution.   Make sure there are no compile errors in the build Output window. If the build succeeded, an executable file named "ADXL335SerialTest.exe"  will be created in sub directory (usually  ADXL335SerialApp/ bin/Release or bin/Debug). The exact file location of the executable can be found in the build "Output" window.

Run the Application

8. Double click on the executable file to run the application. A window with the following screen should appear. The white text box area is where exception messages will appear if they occur. 

9. Now make sure the Teensy accelerometer USB is plugged in. 
10. Press the "Start" button on the screen to start controlling the X, Y, Z axis lines with the Teensy Accelerometer.

If the accelerometer is sitting on a flat surface, only the blue line representing the Z axis will be visible as shown below.

11. Try rotating the Teensy Accelerometer so that the X or Y axis is pointing upward. The lines on the screen will change in real time as you rotate the accelerometer. 

12. Press the Stop button to stop listening to the serial port when your done.

Saturday, May 10, 2014

ADXL335 Accelerometer on the Teensy 3.1 - Getting Started

This is a little project to get started with the Teensy 3.1 and a triple-axis accelerometer. I want to get data from the accelerometer in a form that can be used by an application so the code in the end normalizes the values to the G forces measured and outputs the values o the USB serial port.

This project only requires a couple parts. You will also need some wire,  a small breadboard and a micro USB cable. You will also want the pin out for the Teensy 3.1.

Parts List

Total Cost  $35

Step 1 - Circuit Setup

I used analog input pins A0, A1, and A2 for the x,y,z outputs from the accelerometer and powered the accelerometer directly from the 3.3V output of the Teensy. I soldered headers onto the the Teensy's side pins to make it breadboard friendly.

Step 2 - Programming Environment Setup

The Teensy can be programmed through the Arduino IDE with the Teensyduino add on and a micro USB cable. Many of the Arduino libraries are also compatible with the Teensy. 
  1. Download and install the Arduino IDE if you do not already have it.
  2. Download and install the Teensyduino add on for the Arduino IDE.
  3. Download the Teensy loader program for your OS .
Next we need to calibrate the Accelerometer.

Step 3 - Accelerometer Calibration 

We need to determine the max and min values for each axis of the accelerometer. To do this, you need get multiple readings with the accelerometer oriented in the min and max positions along each of the axis. The values will be used as constants in the code that will run on the Teensy to get scaled readings.

I used a modified procedure based on the calibration instructions on the Adafruit learning site to calibrate my accelerometer because I didn't want to do any additional hardware setup. 

Compile and Load the Calibration code

  1. Download the ADXL335 Calibration sketch and open it in the Arduino IDE.
  2. Open the calibration sketch in your Arduino IDE. 
  3. Plug in the Teensy micro USB cable.
  4. Select Teensy 3.1 as the board under Tools -> Board -> Teensy 3.1
  5. Verify that the correct COM port is selected for the Teensy under Tools->Serial Port. (It will probably be the only one shown unless there are other COM devices connected to your computer.)
  6. Compile/Verify the sketch by typing Ctrl+R or clicking on the check mark icon near the top left corner.
  7. When the sketch is done compiling, the Teensy Loader will open automatically. 
  8. With the Teensy Loader in Auto mode (the Auto button is green as shown below), press the button on the Teensy board to upload the calibration code.

Perform the Calibration

  1. Open the Serial Monitor under Tools-> Serial Monitor in the Arduino IDE.
  2. Set the baud rate. The baud rate can be set to 38400 using the drop down at the bottom right corner of the Serial Monitor window. 
Measure Z-Max 
  1. Place the Accelerometer circuit on a flat surface to get the Z-max value.
  2. Send a "1" to the Teensy using the Serial Monitor Send feature to run the calibration code. You should see output in the Serial Monitor as shown below. Notice that the upper range for Z is now 612, this is the max value for Z when the board is at rest. The X and Y Min values have changed too, but we are not done with those yet.

Measure Z-Min
  1. Hold the Accelerometer circuit upside down against a flat surface(such as the underside of a table) to get the Z-min value. (Hold it still during the measurement). 
  2. Again, send a "1" to the Teensy using the Serial Monitor Send feature to run the calibration code. A second calibration output will appear in the Serial Monitor as shown below. Now the lower range for Z will have changed, in my measurement, it was measured at 413 as shown below. 

Measure the Y-Max, Y-Min, X-Max, and X-Min Values

Repeat the procedure above with the circuit oriented in the Max and Min positions for the X and Y axis's using the following orientations:

Y-Max:  Y arrow on the accelerometer should be pointing straight up. 
Y-Min:   Y arrow on the accelerometer should be pointing straight down.
X-Max:  X arrow on the accelerometer should be pointing straight up.
X-Min:   X arrow on the accelerometer should be pointing straight down.

The min max values for each axis are retained through calibration runs so the final output will have the min and max ranges for the raw values for each axis. These values will be used as constants in my code to normalize the output values.

Step 4 - Program the Teensy

Now that we have the min max values to use, we use the values in code to send normalized values between 1 and -1 for the x, y, and z orientations detected by the accelerometer.
  1. Download the Teensy Accelerometer Code
  2. Open the TeensyAdxl335.ino sketch and change the min/max values for each axis to the values measured in the calibration above. 
  3. Save and Verify/Compile, and upload the code to the Teensy using the same procedure described above to upload the calibration code.
  4. Use the Serial Monitor to verify the output from the Accelerometer. You should see the out values scrolling. The output should look like the view below.

Friday, February 21, 2014

Netduino 2 Getting Started

While I'm waiting for my other parts to come in, I got one of these Netduino's a while back to try out. After all, most of my programming experience is in .Net, not C! So for $35 I figured this board is worth a try. The board touts an ARM 7 processor with multi-processing capability and a form factor that almost exactly matches the Arduino Uno. So all the Uno proto shields can be used with this board. You can write code for it using Visual Studio and C# which is pretty sweet.

Getting started is pretty simple, especially if you already use C#.Net for other programming projects.
You'll need to install 3 things to get going:

  1. MS Visual Studio C# Express 2010
  2. Net MicroFramework 4.2 SDK
  3. Netduino SDK v4.2.2.0 (32-bit) or Netduino SDK v4.2.2.0 (64-bit)

And of course.. you need a Netduino 2 ($34.95)

To create a new Application for the Arduino 2, open Visual Studio and create a new project.
When the dialog comes up select Micro Framework and Netduino 2 Application.

I want to debug on the real hardware, not using the Emulator. To do this I'm going to set the Project properties for the .Net Micro Framework:

  1. Make sure the Netduino is plugged into the computers USB port so it will show up in the device list.
  2. Change the Transport to USB and select Netduino2_Netduino as the device.

That's all it takes to be able to debug your code on the hardware. I can now run my code in debug mode, directly on the Netduino 2!

Now just write a little code to blink the blue on board LED (to the right of the board) in program.cs. Here is some code:

namespace NetduinoApplication1
    public class Program
        public static void Main()
            // Create an Output port for the Onboard led pin and set it to false.
            OutputPort led = new OutputPort(Pins.ONBOARD_LED, false);

            // Blink the LED

        // Blink the LED at 250ms on/off intervals
        public static void Blink(OutputPort led)
            while (true)
                led.Write(true); // turn on the LED
                Thread.Sleep(250); // sleep for 250ms
                led.Write(false); // turn off the LED
                Thread.Sleep(250); // sleep for 250ms


Press the run button to start debugging, the blue LED will blink..  Hello World Netduino!

More information about the Netduino can be found at

Sunday, February 2, 2014

Trinket-izing the 434Mhz RF Transmitter

434MHz RF Transmitter with the Trinket
The transmitter side of the 434mhz RF Transmitter/Receiver with the Arduino Micro  doesn't really do much processing. It doesn't really need all of the functionally of the Arduino Micro just to collect a little temperature reading and send it the RF Transmitter! The Adafruit Trinket has plenty of power and space for the processing needed, with the added benefit that it shrinks the size and the cost of the project!

Parts List

Temperature Sensor and RF Transmitter:
RF Link Transmitter - 434MHz ($3.95)
Adafruit Trinket 3V Logic   ( $7.95)

Total Cost  $14

Click here to get the code for this project ...

Serial Communications on the Trinket
The Trinket doesn't have is a serial interface like most Arduino boards have. Fortunately there are ways around it! With a little research, I found there are three main methods being used to get serial communications with the Trinket:

  1. Use Virtual Wire to simulate it. I tried a couple of versions of this but I could not get this to compile. Some people also seem to write their own implementation of this.
  2. Use Software Serial to turn a couple of pins into an RX/TX. The plus side of this is that it works! The downside is that it takes a lot of memory so you may not have much room left for other stuff if you use this. Pulling in the Software Serial put the size of the Transmitter/Temperature reading sketch up to 5,058 bytes, which still fits on the Trinket!
  3. Another option - use the UsiSerial library posted by Frank Zhao to implement a hardware serial port. The upside of this is a much smaller foot print! Using the UsiSerial, my compiled sketch is only 3,666 bytes! Plenty of room left! Unfortunately, while this compiled and loaded, it didn't work. Maybe because I am using the 3 Volt Trinket? The notes say it was tested on the 16MHz trinket which I believe is the one with 5 Volt Logic.

Circuit Setup

434MHz RF Transmitter Connections:
GND  -> Ground on Trinket
DataIn -> Software Serial TX pin 1 on Trinket
Vcc     -> 3V from Trinket
ANT   -> 13 cm wire used as an antenna

TMP36 Connections:
Vcc  -> 3.3V on Trinket (TMP36 Pin 1 on left when looking at flat side of sensor)
Vout -> Pin 2/AnalogRead(1) on Trinket (TMP36 Center Pin)
Gnd  -> Ground on Trinket (TMP36 Pin 3 on right when looking at flat side of sensor)

Trinket Transmitter Temperature Sensor Circuit

Sunday, January 26, 2014

434Mhz RF Transmitter/Receiver with the Arduino Micro

I wanted to experiment with the RF Link transmitter/receiver for my wireless projects. With the temperature around here going from below 0 to 60 degrees, a wireless temperature sensor would be nice! The project is to get data from an analog temperature sensor and use an RF link to transmit the data to a receiving device.

The Parts List:

Temperature Sensor and RF Transmitter:
Arduino Micro Board  ($22.95) 

RF Receiver side data collection and processing:
RF Link Receiver - 4800bps (434MHz) ($4.95)
 Arduino Mega 2560 I had this on hand, however a Micro, Uno or other Arduino board can be used instead as long as it has a UART + USB Serial (if you want to use it).

Total Estimated Cost ~  ($29 for Transmitter  +$28 for Receiver)

Click here to get the code for this project

Circuit Setup

The RF Link receiver and transmitter pair are the interesting part of this project. With these two guys, you can add one way communications with only a UART on each side.  I choose to use the Arduino board serial since I happened to have a couple of boards on hand and using the serial interface from these boards is very easy compared to the other ways of getting the serial data these components (i.e. software serial or virtual wire). This RF Link pair gets A LOT of noise, and that noise comes in as garbage data that has to be filtered out using a protocol that is robust enough to recognize the data you want to send and receive. The protocol and filtering is the key to getting reliable data from these guys!

Hooking up the RF Link Receiver

Here is the pin out for the RF Link receiver from the datasheet. Even though it has 8 pins, It's really four connections, Ground, 5V power, Digital Out to the RX of the serial port and the antenna on Pin 8.

Pins 1, 6, 8    -> Ground  from Arduino Mega
Pin 8              -> 13 cm wire to act as an antenna
Pins 4, 5         -> 5V from Arduino Mega
Pin 2              -> Connected to RX3 (pin 15 on the Arduino Mega)

Hooking up the RF Link Transmitter to the Arduino Micro

Here is the datasheet for the RF Transmitter module. This module only has 4 pins so it's pretty easy to hookup. I used 5V to power it from the Micro but it can actually take up to 12V if you want better range!

GND  -> Ground on Arduino Micro
DataIn -> TX pin on Arduino Micro
Vcc     -> 5V from Arduino Micro
ANT   -> 13 cm wire used as an antenna

Hooking up the TMP36 Temperature Sensor

Adafruit has an excellent tutorial to explain how to hook up the temperature sensor and much more Adafruit TMP36 sensor tutorial.

Vcc   -> 3.3V on Arduino Micro                 (TMP36 Pin 1 on left when looking at flat side of sensor)
Vout  -> A0 analog input on Arduino Micro (TMP36 Center Pin)
Gnd   -> Ground on Arduino Micro             (TMP36 Pin 3 on right when looking at flat side of sensor)

The datasheet also shows a 0.1uF power supply coupling capacitor from the supply voltage pin to ground. I added this directly accross the leads on the TMP36 to help regulate any input voltage fluctuation. (not shown in picture below).
I also used the Analog Reference voltage at 3.3V instead of the 5V default by connecting the 3.3V pin on the Micro to the AREF pin (just to the right of the 3.3V pin).

CAUTION: If you connect the GND pins and Vcc pins backwards, your TMP36 will get very very hot and eventually this will burn out your sensor!

RF Transmitter and Temperature Sensor Circuit

The Code

The challenge in creating an RF link with these components is filtering out the bad data so that you can more reliably get the data you want!  These guys make a pretty noisy RF link so you can expect to get lots of garbage data (at least when using 5V to power the transmitter). The way to filter out the garbage data is to establishing a protocol for sending and receiving data.

Basically, a protocol is an agreed upon data format that is unlikely to occur in random data. Having a protocol allows the receiving code to know what to expect. There are a lot of ways to do this. You might send begin and end markers around the data and check to make sure you got both on the receiving side. A protocol may also send and check the size of the data packet along with the data to help the receiving side verify that the amount of data received is correct. The transmission could include the CRC of the data packet and the receiver could check it on the other end to verify that the data received is what was expected.
You can't prevent the receiver from getting bad data, but you can decide what the receiver will do with it.

I choose to establish a very simple protocol for my project using the word "Temp" as a sequence of characters that will proceed each temperature reading sent by the Transmitter. The temperature reading is a decimal and can be either a positive or negative number. So the only valid data the receiver should ever expect to get would look something like:

The receiving code will exclude all data that doesn't match the expected data format established above. Ascii character codes are used for filter data. If the word Temp is not received or if bad data that doesn't meet the criteria for expected data, the data should be ignored. The received data is not always perfect so validation still needs to be added to ensure that only good data is used. Also, the transmitter is set to send a new value every 5 seconds, this is probably more often then I would like but it is good for testing!