Google+

Wednesday, 25 December 2013

3-Wire HD47780 LCD for less than 1 dollar

In this instructible we will learn how we can hook up an LCD based on the HD44780 chipset to the SPI bus and drive it with only 3 wires for less than $1. Although I will focus on the HD44780 alphanumeric display in this tutorial, the same principle will work pretty much the same for any other LCD which uses an 8 bit parallel data bus, and it can be very easily adapted to suit displays with 16 bit data buses.
The HD44780 (and compatible) based alphanumeric displays are usually available in 16x2 (2 lines consisting of 16 characters) and 20x4 configurations, but can be found in many more forms. The most 'complicated' display would be a 40x4 display, this sort of display is special as it has 2 HD44780 controllers, one for the upper two row and one for the bottom two rows. Some graphic LCDs have two controllers as well.

The HD44780 LCDs are great, they are very cheap, readable and quite easy to work with. But they also have some drawbacks, these displays take up a lot of I/O pins when connected to the Arduino. In simple projects this is not a concern, but when projects get big, with a lot of IO, or where certain pins are needed for things such as an Analog read or PWM, the fact these LCDs require a minimum of 6 pins can become a problem.

But we can solve this problem in a cheap and interesting way.

Step 1: Getting the components

I used TaydaElectronics for most of the components I used in this project. You can get these parts on ebay as well, but for ease of use, I'll link you to Tayda.

Shopping List
74HC595 package DIP16
Generic male header - 2 pins. This is not required, I used this as a way to permanently disable backlight.
Ceramic Capacitor - capacitance 0.1µF; voltage 50V
Electrolytic Capacitor - capacitance 10µF; voltage 35V
Ceramic Capacitor - capacitance 220pF; voltage 50V
NPN-Transistor - part # PN2222A*
1k Ω Resistor
Trimmer Potentiometer - maximum resistance 5kΩ
470 Ω Resistor
With an NPN transistor the backlight will stay off until it is turned on by software. If you want to have the backlight on by default, use a PNP type transistor. Changes in the code of the library provided will have to be made, though.

Sub total for this list is $0.744. The pin header is also not required, so you can save 15cents right there and the subtotal will be $0.6.

Step 2: Know your hardware #1

Here is a standard pin out of a HD44780 LCD, it is also very similar to some graphic LCDs as well.
The HD44780 can work in two modes:
1. 4-bit mode, where each byte sent to the LCD consists of 2 4-bit parts.
2. 8-bit mode, on which we will focus.

The LCD has 16 pins in total, 3 control pins and 8 data pins:
RS - Controls whether we want to send a command or data to the LCD. Where 'high' means data (a character) and 'low' means a command byte.
R/W - The HD44780 controller allows you to read from its RAM. When this pin is 'high' we can read data from its data pins. When it is 'low' we can write data to the LCD. Although the option to read from LCD can be useful in some cases, we will not go over it in this tutorial, and we will simply ground this pin to ensure that it is always in Write mode.
- E is the 'Enable' pin, this pin is toggled 'high' then 'low' to write the data to its RAM and eventually display it on the screen.
DB0-7 - These are the data pins. In 4-bit mode we only use the 4 high bits DB4-DB7, and in 8 bit mode all of them are utilized.
VSS - This is the ground pin.
VCC - This the power pin, the LCD runs off a 5V power supply, we can easily feed it power from the Arduino's +5v pin.
Vo - This is the pin which allows you to set the contrast level for the display, it requires a potentiometer, normally a 5K Ohm pot is used.
LED+ - This is the power source for the backlight. Some LCDs do not come with a backlight, and only have 14 pins. In most cases this pin also requires a +5v connection.
LED- - This is the ground for the backlight.*
* It is important to check the displays datasheet or inspect its PCB to check for a backlight resistor, most LCDs will have them built-in, in which case all you have to do is apply power to LED+ and ground to LED-. But in the case your LCD doesn't have a built-in resistor for the backlight, it is important that you add one, otherwise the backlight will consume a lot of power and it will eventually burn out.

In most cases the way this LCD is wired to the Arduino is by using it in 4-bit mode and grounding the R/W pin. This way we use pins RS, E and DB4-DB7. Running in 4-bit mode has another small disadvantage in that it takes twice as long to write data to the screen as it would take in an 8-bit configuration. The LCD has a 'settling' time of 37 microseconds, this means you have to wait 37 microseconds before sending the next command or data-byte to the LCD. Since in 4-bit mode we have to send data twice for each byte, the total time it takes to write a single byte goes up to 74microseconds. This is still fast enough, but I wanted my design to produce the best possible results.

The solution to our problem with the number of pins used lies in a Serial to Parallelconverter...

Step 3: Know your hardware #2

What we will do is build an adapter which takes a serial type of communication coming out of the Arduino and converts the data into a parallel output which can be fed to our LCD.

In comes the 74HC595 chip. This is a very cheap and simple to operate shift register. In essence what it does is take in a clock and data signals which it uses to fill an internal 8 bit buffer with the 8 last bits that were 'clocked in'. Once the 'Latch' (ST_CP) pin has been brought 'high' it moves these bits into its 8 outputs. The 595 has a very nice feature, it has a serial data out pin (Q7'), this pin can be used to daisy chain 2 or more 595's together to form Serial to Parallel adapters which are 16 or more bits wide. For this project we will need 2 of these chips. The schematic can also be modified to work with a single 595 in 4-bit mode, but this won't be covered by this tutorial.

Step 4: Wiring it all up

Now that we know how our hardware works we can wire it all up.
In the schematic we see 2 595 chips daisy chained together to form a 16 bit parallel output.
The bottom chip is actually the main one, and the upper one is daisy chained to it.

What we see here is that the bottom 595 is driving the LCD's data pins in an 8-bit configuration, the top chip controls the RS signal and backlight by turning a transistor on or off. Remember the *note about the LCD backlight on Know your hardware #1 page, in the case your LCD doesn't have a backlight resistor, don't forget to add one in your circuit. In my case the LCDs I have already come with a resistor built-in, so I skipped this step.

The contrast is applied through a 5K Ohm pot, one pin goes to GND the second one goes to VCC and the wiper to the Vo pin on the LCD.

The capacitors used on the LCD's and 595's VCC lines are decoupling capacitors, they are there to get rid of interference. They are not a must if you are working on a breadboard, but should be used in case you build your own version of this circuit to be used outside of "lab conditions".

R5 and C9 in that very specific order create an RC delay, which makes sure that the data in the 595's outputs has time to stabilize before the Enable pin on the LCD is set 'high' and reads the data.

Q7' of the bottom 595 goes into the serial data input of the 595 on the top, this creates a daisy chain of 595s and thus a 16 bit interface.

Wiring up to the Arduino is easy. We use a 3-wire configuration, using Arduino's SPI pins. This allows for very fast data transfers, sending 2 bytes to the LCD usually takes about 8 microseconds. This is very fast, and it is actually much faster than the time it takes the LCD to process the data, thus a delay of 30 microseconds is needed between each write.
One very big benefit of using SPI is that pins D11 and D13 are shared with other SPI devices. This means that if you already have another component which uses SPI, such as an accelerometer, this solution will only use one extra pin for the enable signal.

On the next page we will see the result. I have built a backpack on a perfboard and it is working very well for me so far.

Step 5: The result + Library

"A picture is worth a thousand words", I agree with this statement, so here are some images of the end result for this project.

These are images of the completed product, the Fritzing PCB view is the perfboard layout I used to build my backpack. You may find it useful if you want to build your own.

I liked it so much that I designed a PCB using DipTrace and ordered a batch of 10 PCBs. I will need 2 or 3 units for myself but will make the rest available for a symbolic price when I receive them. So if anyone is interested please let me know.

* Edit: The PCBs are here, and they work. Here's the full picture gallery for this project, including the actual PCBs.
http://imgur.com/a/mUkpw#0

Of course I did not forget the most important thing, a library to use this circuit with.
It is compatible with the LiquidCrystal library included with the Arduino IDE, so you can easily replace the declarations at the top of your sketch and not have to change anything else in your sketch. There is also an example sketch which demonstrates how each function in the library works, so check it out.

Read More


Tuesday, 24 December 2013

Stress Makes Art: Galvanic Skin Response and Visual Generation

This piece takes the galvanic skin response value of the user and uses it to fuel the creation of a visual on screen. Galvanic skin response is thought to be correlated to a person's stress level and is used in lie detectors. In this particular work, the GSR value affects the speed at which a black growth is visualized on screen. This represents the idea that the more stressed we are, the faster diseases and other negative consequences can spread.


The hardware part of this project is fairly straightforward and uses an Arduino Uno board and the following other materials:
- Arduino Uno w/usb connector
--Breadboard
- 2 250K resistors, in a series
- Jumper wires
- Stranded wires
- 2 ring terminals (or other metal objects to place fingers on)
- Solder + soldering iron

The more complicated part of this project was coding in the Processing environment. These instructions will be in two main steps, "Hardware" and "Code" with a brief mention in step three of the construction of the enclosure for the electronics.

Step 1: Hardware

To make the sensors, I soldered the two ring terminals to jumper wires (you can also use stranded wires) and connected the wires to the breadboard as noted in the photograph and schematic. One wire is connected to 5V and the second wire is connected to GND through two 250K resistors in a series. This second sensor's wire is also connected to the A0 terminal on the Arduino. These connections to the Arduino are all made via the breadboard.

Step 2: Code

For the coding part of this project, I referred to the two sources below. You don't need to look at these sources unless you want to understand them in their original form. If you just want to copy/paste code that works, skip to 3) My Code.

1) GSR Source Code
The first was http://cwwang.com/2008/04/13/gsr-reader/ which includes the Arduino code (for Arduino and Processing to communicate) and the Processing code to use the galvanic skin response data from the constructed sensors. Wang's code basically charts a person's galvanic skin response value in a moving line graph, which looks a little like an EKG reading visually. I wanted to have a more abstract visualization of the data so used code from another source to generate the visuals.

2) Visual Source Code
The code to create the visuals is from: http://www.generative-gestaltung.de/P_2_2_1_01

3) My Code


// you can copy/paste this code into a new Processing sketch
// Visual source code from: http://www.generative-gestaltung.de/P_2_2_1_01
// GSR source code from: http://cwwang.com/2008/04/13/gsr-reader/

import processing.pdf.*;
import java.util.Calendar;

boolean recordPDF = false;

import processing.serial.*;
Serial myPort;


int hPosition = 1;   
float currentReading;
float lastReading;
int count=0;
int zeroLinePos=0;

float gsrAverage,prevGsrAverage;
float baseLine=0;
long lastFlatLine=0;
int baselineTimer=10000;//10 sec
int gsrValue;
int gsrZeroCount=0;
float gsrRange=0;
int downhillCount=0;
int uphillCount=0;
boolean downhill;
boolean peaked=false;
float peak, valley;
int speed ;
int NORTH = 0;
int NORTHEAST = 1;
int EAST = 2;
int SOUTHEAST = 3;
int SOUTH = 4;
int SOUTHWEST = 5;
int WEST = 6;
int NORTHWEST= 7;

float stepSize = 1;
float diameter = 1;

int direction;
float posX, posY;
int minCurrentReading = 1000;
int maxCurrentReading = 0;

void setup() {
  size(800, 800);//size of window for image
  background(255);
  smooth();
  noStroke();
  posX = width/2;
  posY = height/2;
  println(Serial.list());
  currentReading=0;
  lastReading=0;
  gsrAverage=0;

//find the right serial port for your computer and enter in the number inside []
  myPort = new Serial(this, Serial.list()[8], 9600);
}

void serialEvent (Serial myPort) {
  int inByte=myPort.read();
  //0-255
  gsrValue=inByte;//taking value sent from Arduino
}


void draw() {

  calculateGSR();

  println("currentReading = " + currentReading);

  // map currentReading to speed
  if (currentReading <= 50)
  {
    currentReading = minCurrentReading;
  } else  if (currentReading > 1000)
  {
    currentReading = maxCurrentReading;
  }
  else // valid zone
  {

  if (currentReading< minCurrentReading)
  {
    minCurrentReading = int( currentReading);
  }

   if (currentReading> maxCurrentReading)
  {
    maxCurrentReading = int(currentReading);
  }}

println("currentReading = " +  currentReading + " minCurrentReading = " + minCurrentReading + " maxCurrentReading = " + maxCurrentReading);
   currentReading = map (currentReading, minCurrentReading,maxCurrentReading,10,15000);
   speed = int (currentReading);
 
  println("mapped value = "+  speed);
    delay(50);//delay for stability
  
//applying the GSR reading to drive the speed of that the organic drawing "grows"
  for (int i=0; i<=speed; i++) {
    direction = (int) random(0, 8);

    if (direction == NORTH) {
      posY -= stepSize;
    }
    else if (direction == NORTHEAST) {
      posX += stepSize;
      posY -= stepSize;
    }
    else if (direction == EAST) {
      posX += stepSize;
    }
    else if (direction == SOUTHEAST) {
      posX += stepSize;
      posY += stepSize;
    }
    else if (direction == SOUTH) {
      posY += stepSize;
    }
    else if (direction == SOUTHWEST) {
      posX -= stepSize;
      posY += stepSize;
    }
    else if (direction == WEST) {
      posX -= stepSize;
    }
    else if (direction == NORTHWEST) {
      posX -= stepSize;
      posY -= stepSize;
    }

    if (posX > width) posX = 0;
    if (posX < 0) posX = width;
    if (posY < 0) posY = height;
    if (posY > height) posY = 0;

    fill(0, 40);
    ellipse(posX+stepSize/2, posY+stepSize/2, diameter, diameter);
     //send 'a' for more bytes
  }
}


void calculateGSR () {
  //best delay setting for gsr readings
  //println(gsrValue);
  delay(50);
  //image(myMovie, 0, 0);

  if (gsrValue<15 &&gsrValue>-15){ // anything between -15 and +15 is considered zero
   //if someone lifts fingers off for 10 seconds resulting in 10 0s, just reset

    if( gsrZeroCount>10){
      currentReading=0;//flatline
      gsrAverage=0;
      baseLine=0;
      lastFlatLine=millis();
      gsrZeroCount=0;
      // println("reset");
    }
  
    gsrZeroCount++;
  } // end of test for close to zero

  else{ // ggood reading
    currentReading=gsrValue-baseLine;
    gsrZeroCount=0;
  }

  if(millis()-lastFlatLine>baselineTimer){
    baseLine=gsrAverage;//if we got at least 10 seconds of reading since the last flatline
  }


  gsrRange=peak-valley;



  gsrAverage=smooth(currentReading,.99,gsrAverage);

int thres=7;

  if (currentReading-thres>lastReading && peaked==true){
    downhill=false;
    //println(downhillCount);
    uphillCount++;
    downhillCount=0;
    point(hPosition-1, height/2.0-lastReading);
    valley=lastReading;
    peaked=false;

  }
  if(currentReading+thres<lastReading && peaked==false){
    //println(uphillCount);
    downhill=true;
    uphillCount=0;
    downhillCount++;
    point(hPosition-1, height/2.0-lastReading);
    peak=lastReading;
    peaked=true;
  }

  prevGsrAverage=gsrAverage;
  lastReading=currentReading;
  //send 'a' for more bytes
  myPort.write('a');

}


int smooth(float data, float filterVal, float smoothedVal){
  if (filterVal > 1){      // check to make sure param's are within range
    filterVal = .99;
  }
  else if (filterVal <= 0){
    filterVal = 0;
  }
  smoothedVal = (data * (1 - filterVal)) + (smoothedVal  *  filterVal);
  return (int)smoothedVal;
}

Step 3: External Design/Enclosure (silver box with black hand)

If you want to make a simple paper box enclosure for the electronics, you can look at this box template. I made the box with metallic cardboard and printed a hand mark on top so that people at the exhibition knew to place their hand on the box to start the experience. This is obviously optional and there are many ways to make sturdier enclosures.
Read More


Building Your First Android Application

More than ever before, the world is mobile. Of this mobile revolution, Android is one of the top platforms. Put out by Google to compete with Apple's iOS, Android shows no signs of slowing down. People are wanting to build the apps that run on Android. You always hear about the success stories of apps getting bought for millions of dollars such as Draw Something or Instagram, and now you can start the path to building your million-dollar idea.

Step 1: Installing Java

Android apps are written in a programming language called Java. Java is one of the most popular programming languages in the world and helps run billions of devices. One of the great things about java is that it is completely free to download. It was originally created by Sun Microsystems, but was purchased by Oracle in 2010. To download java onto your computer go to https://www.java.com/en/ and click on the "Free Java Download" button. This will take you to a page where you can start the download. Once you click the button "Agree and Start Free Download" a file will be downloaded. Once the file is download, run the .exe file. When the install file opens up follow the steps to finish the Java installation.

Step 2: Downloading the Development Environment

There are a number of ways to develop Android apps. The easiest way to get started quickly is to use the ADT Bundle developed by Google. The ADT Bundle provides a number of tools that are essential to building android apps.

To start go to https://developer.android.com/sdk/index.html. Once on this page click on the button "Download the SDK ADT Bundle". Once this button is clicked check the box agreeing to the terms and conditions and select either 32-bit or 64-bit, depending on your computer. After you have agreed and selected your system type click on the "Download the SDK ADT Bundle" button and the download will start. The download is a fairly large .zip file (460 mb) so it may take ahwile. After it has completed downloading you can move on to learn how to install it!

Step 3: Installing the ADT Bundle

With the file done downloading, double-click to open it. Extract all the files to a location on your computer. I left it the default location when I extracted. Once the file is finished extracting click on the file. You should now see two folders named eclipse and sdk and an application called SDK Manager. We are going to open up the environment where you will be developing android apps so click on eclipse. You should now see multiple folders and multiple files. Here you want to double click eclipse.exe to open the application.
With eclipse open we can now get started building our first app!

Step 4: Running the ADT Bundle

When you start up the eclipse you get a screen that asks you wear you want to save your files. Go ahead and leave this default. It should be \path\to\folder\workspace. This is wear all of your files and folders that you create within eclipse will be saved.

Step 5: Building your first App!

After selecting your workspace go to File -> New -> Android Application Project. This brings up a new application window for you to fill out the specs of your app. Type "Hello Wold" into the Application Name space. This will be the name of your application that gets shown in the Play Store when people try to download it. When you fill out the name space all other spaces will automatically fill out with it. When your screen looks like my new application image click next. On the next screen leave everything how it is and click next. On the next screen you can select your apps icon. For now, just leave it set as the default and select next. The next screen has you select an activity. Leave Blank Activity selected and click next. On the final screen keep everything how it is and select Finish. After you click finish your app is now created! Next we show you how to add stuff to the screen.

Step 6: Programming your App

With your new app open, we now want to see how to change what the user will see. The ADT Bundle gives us a great tool with a visual editor to create our apps. To get to this click the activity_main.xml tab that is open. If you do not see it, in the file manager on the left select res -> layout -> activity_main.xml. This opens the visual editor. From the visual editor click on the smaller text "Hello world!" located on the screen. When this is clicked a line to the right under properties highlights. Click on the text @string/hello_world to change it. Your text has to have the @string/ in front of it though. This is a part of the xml so that Android knows what type it is. Play around with the visual editor for a bit. When you finish your app, go on to figure out to test it.

Step 7: Creating the Device to Test Your App

There are two ways that you can test your app. You can either put it on to an android device and run it, or you can set up an emulator to test on. Since not everyone has a device to test on we'll set up an emulator. The youtube video created by user Andr.oid Eric shows how to create an Android Emulator using the Android Virtual Device Manager.


Step 8: Testing Your App

Now that your have your app and you have your device to test it on it's time to put the two together! To test your app on the emulated device you first need to start up your emulated device. My emulated device is a Nexus One so your home screen may look different. When your device is up and running (give it some time, it takes awhile to get started) you then go back to eclipse and click the green play button. Once pushed, eclipse will put your HelloWorld app onto the emulator and run it. Congratulations, you have now created your first android application!

Step 9: Thank you

I hope that the steps were easy to follow and that everything went smoothly. Now that you know how to start developing apps, go out and build your million-dollar idea!
Read More


DIY Android Ball Maze - An Introduction to the Android ADK

Maze 014.jpg
"joystick" controller
Maze 017.jpg
Introduction
If you're reading this article you're probably like me: I go through phases where I get so engrossed in a project (which most others would see as trivial), so focused on the goal that sleep and food are afterthoughts, I put my body through a gauntlet to appease some primitive urge of mine to CREATE.

Such was the beginnings of this project. I attended Google I/O 2011 and managed to get my hands on an Android ADK demo board. ADK is the Accessory Development Kit , an Arduino-based interface board whereby you can connect your compatible Android device (2.3.4 and any device from 3.1 onwards) to virtually any hardware and use the phone to control a device, or vice-versa.  It's called the Android Open Accessory platform, and it's totally cool.

To introduce the concept to the Google’s keynote speech they produced a regular ball maze toy , familiar to many, which was controlled by a Motorola Xoom tablet.  This Instructable is kind of two instructables in one: first, I'll be illustrating the steps required to set up the ADK from scratch and then I'll be reproducing Google's ball maze on a Nexus One phone to demonstrate a simple use of the ADK board (I'll keep the massive bowling-ball version for another Instructable).

So continuing with my story: I grew up with a ball maze, my parents had one as far back as I can remember. A little while after I got home from Google I/O I found the maze at my parents’ house and shortly thereafter I discovered I had everything I needed to make my very own Googley maze controlled by my Nexus One.

[Lights on, cue primitive one-tracked mind]

The goal was set: I had one night to make this from scratch, hardware and software. I'd never written a real-world Android app before (not that this is very real-world yet...), but I was convinced that it couldn't be too hard. I worked from 7pm to about 5am, though I probably could have done it in 2-4 hours if I had an Instructable like this to start with - being my first ever Android project, much of that time was reading!

Only the Nexus One (Gingerbread 2.3.4) has been tested with the code I'm supplying, but it should work with little to no modifications on a stock up-to-date Nexus S and possibly also Android 3.1 tablets.  As of writing, I am unaware of any other supported devices or Android versions.

So dig through grandma’s game closet for that old ball maze, grab your Nexus, break out your Google ADK board if you went to Google I/O (or get a compatible one from the suppliers listed here ) and start building!

Concept
The idea is relatively simple: monitor the phone’s accelerometer, and translate the three-dimensional acceleration vector (ie. which way is "down") into a coordinates on a two-dimensional plane - one dimension for each servo or axis of rotation on the maze.  This is mapped to two absolute positions between 0-255 for positioning the servo arms. These values are passed to the ADK board which acts as the servo controller and controls the tilt on the maze.

In other words, you can now play the ball maze game by using your phone as a remote controller!

Step 1: Materials and Tools

Materials
- A ball maze / labyrinth game
- Google’s ADK Demo board or compatible ADK board with 2 servo outputs
- Two small servos (eg. mini servos found in small RC cars/helicopters)
- Google Nexus One or Nexus S with Gingerbread 2.3.4 (not tested on Nexus S)
- Short cable with female 3x2 or larger box connector (an internal USB panel patch cable works well)
- Male box connector pins - either: one 3x2 or two 3x1 (for connecting to servo sockets)
- 0.5mm aluminium or other pliable sheet metal (for servo brackets)
- Small springs or springy metal (eg. I used stainless steel strips found in some wiper blades)
- A small block of wood (For mounting the "inner" servo to the ring)
- Thin stiff wire, eg. paperclip wire (for servo lever arm fixtures)
- Assorted small screws (to secure servo brackets)
- Small tacks, nails or a staplegun (to secure springs in place)
- Cable ties
- A few drops of oil or grease, particularly if your maze is 30+ years old like mine :)

Required tools:
- Drill and drill bits (I used 1mm, 6mm bits)
- 1-2 pairs of small needle-nosed pliers
- Wire clippers
- Screwdrivers
- Soldering iron
- Sharp knife / craft knife

Other useful tools:
- Drill press
- Small hand-held rotary drill/grinder tool (Dremel or similar)
- Diamond-tipped engraving bit or drill bit (for drilling holes in stainless steel spring strips)
- Bench grinder
- Small hammer / tack hammer

Note to the lazy
If you really don't want to compile and install the apps to your phone (which Ihighly recommend, you'll see why later), you can download the APK files from this Instructable.  You must ensure that the Settings > Applications > Unknown sources option is selected, copy the APK files to your device, then use a program like ApkInstaller to install them.  If you get an error, check your Android version is either 2.3.4 or 3.1 or greater.

Step 2: Setting up Android Development Software (Eclipse)

To compile the source code you'll need an Android development environment, and the easiest one to set up and use is probably Eclipse.  The entire installation process is well documented on this page, but here are the basic steps:

1. Download the appropriate installer for your operating system and install (choose the "Eclipse Classic" version).

2. Download the Android Software Development Kit (SDK) and install it.

3. Download and Configure the Android Development Tools (ADT) for Eclipse.

4. Add Platform support for the Platform APIs and Google APIs.  If installing on a Nexus One or Nexus S you will need the following:

    SDK Platform Android 2.3.3, API 10
    Google APIs by Google Inc., Android API 10

 ...whatever the latest revision is for each.  While the API is for version 2.3.3, the minimum Android version requirement on Gingerbread handsets is 2.3.4, which is currently only on stock Nexus One and Nexus S phones.   If you want to try this with an Android tablet running version 3.1 or later, you will need the following instead:

    SDK Platform Android 3.1, API 12
    Google APIs by Google Inc., Android API 12

Note that there is currently no support for Android version 3 devices prior to version 3.1, and I believe it is unlikely to be backported.

Step 3: Install ADK Components and setting up DemoKit

"That's a lot of software to set up", I hear you say...  But you want your maze, so press on!!

ADK Components
Now that you have a functional Eclipse environment, you are ready to set up the ADK components and test the board.  The process is well documented here so I'll only outline the three steps briefly here.  Once you've done this, you are ready to test:

1.  Install Arduino Software (contains libraries and an IDE for coding and installing firmware to the ADK board).
2.  Install the CapSense library (not strictly required for this project, but if you're going to be tinkering with the ADK - which I'm sure you will - you should install this now.  It contains the libraries to sense human capacitance. This is needed for the capacitive button that is located on the ADK shield) .
3. Install the ADK package (contains the firmware for the ADK board and hardware design files for the ADK board and shield) .

Setting up USB Debugging
While we're not going to actually use USB debugging, enabling it provides a quick, easy way to quickly compile, install and test apps on your device.  Follow steps 2 and 3 outlined here to enable USB debugging.

Compiling and Running the DemoKit app
Finally, follow the steps outlined here to get the DemoKit application working on your Android device (if you've followed my steps then you've already done the first step).  When it says "Install the application to your device" , do the following:

1.  On the device, go to the home screen, press MENU, select Applications > Development , and make sure USB debugging is enabled.  You may get a warning - that's fine, it just means that when connected via USB you will be able to install and run applications from Eclipse without any user interaction on the phone.  If you want to be super-protective you can disable this when you're done.
2.  Connect your device via USB
3.  With the DemoKit code open in Eclipse, select Run > Run or press Ctrl-F11.  If you see the Android Device Chooser , just select your Android device and click OK.  Eclipse will upload the compiled package and run it automatically.

Now finally you're ready for some fun!

Step 4: Setting up the ADK Board and Testing with DemoKit

Testing with DemoKit
Without the ADK board the DemoKit application you've just compiled is a little pointless, so once it is running on your phone (you'll see an Android robot with a front panel open), disconnect the USB cord from the computer and (with the other end still attached to the phone) plug it into the ADK board's USB host port.

Plug the power into the ADK board and you should see a power indicator light up on the main Arduino board (under the demo "shield" board which is on top).

Now that DemoKit is installed on your phone you can run it as often as you like - you no longer need to recompile unless you want to make changes.  When connecting the phone to the ADK board, you should get a message like the one shown in the second image - be sure not to check the "Use by default for this USB accessory", because we also want to use the RealMaze program with the ADK board.  Simply click OK to start using it.

The initial screen has a number of hardware input indicators - showing the status of buttons, temperature, light sensors and more.  tap the "Out" tab at the top to show the controls for ADK outputs - relay switching, LED brightness controls and servo controls.

Connect the servos to the ADK board, taking care with the polarity - Black = Ground or -, Red = +, Grey = Signal.

Now you can control the servos using the sliders (second image).  If it's not working check the power light on the board, USB connection, and re-check the servo polarity.  Test the other outputs on the demo shield: lights and relays.

Step 5: Compiling and Running RealMaze

Now for installing and compiling the RealMaze code.  RealMaze is just a severely and shamelessly ripped, hashed-up and duct-taped-together-again version of DemoKit with a bit of code from around the web (sources cited in the code).  It's called RealMaze because all the other accelerometer-based ball maze games are fakes onscreen :)  This one controls the real thing.

There are still many (most?) bits of code, entire classes and resources from DemoKit that I have not removed that are not used, you might want to tidy these up if you want to reuse the code for anything - being an Android amateur I'm worried that it might break if I remove too much!  Code patches and complete rewrites from more experienced programmers will be gratefully accepted, but the point is that it works for me as it is :)

1.  Download the RealMaze.zip file attached to this Instructable and extract the files (with paths intact) in a suitable source code location.

2.  In Eclipse, select File > New Project , then choose Android > Android Projectand click Next.

3.  Type the project name "RealMaze", choose "Create project from existing source"

4.  Check that the Build target is correct for your device (Using Google APIs version 2.3.3 for Nexus or 3.1 for tablets)

5.  Click Finish

6.  Reconnect your phone to the PC then in Eclipse under Package Explorer, right-click RealMaze and select  Run As > Android Application

Similar to the DemoKit installation, you should now have the RealMaze program installed on your phone.  Disconnect the phone from the PC and connect to the ADK board.  You'll see a message similar to the one you got with DemoKit, click OK and you should now be in control of the servos using the tilt on your phone.

(Note: one known bug is that RealMaze does not resume well if you start another activity then try to go back to it.  Simply start it again from the programs list)

Step 6: The Maze Hardware - Preparation

Basic preparation
If the maze you're using is anything like mine was, it might need a bit of thought.  I had to dust it out, oil up the pivot points, and remove hot glue that was used to stick the back on (after it had been dropped many years ago).

If you have better resources than I have, you can probably work out how to put the servos on the outside of the casing, so that they turn the rods just like the knobs usually do.  This may be a better/easier solution for you, but my servos were small, my workshop spares limited, and I kind of liked the old retro-knob look.

Remove the panel on the underside to get at the maze mechanics - this may require removal of screws, wood staples, or in my case an old hot glue repair job.  As you can see, mine had seen the odd repair or two over the years including a very tacky string repair job (that may have been mine at aged 10 after breaking it, I don't recall...).  Notice that I didn't remove any of the existing hardware inside, I've only added to it.  The two tiny servos were easily strong enough to move the tilting deck and the string, rods and knobs that were attached to it.  If your controls are still stiff after oiling you may have to disconnect the old mechanism for this to work more smoothly.

Important note: When referring to the connected wooden parts that make up the tilting maze I will hereafter refer to the outer box as the "casing", the slightly smaller square wooden ring inside the casing as the "ring", and the actual maze which sits inside the ring as the "table".

Servo location
You now need to identify where to put the servos (but we're not mounting them just yet!).  I decided to put mine both in one corner, but you may have to spread yours out.  Here's what I considered when looking for a good mounting spot:

 - You don't want the ball to hit a servo, spring or any wiring when it drops through a hole
 - You also don't want the ball to get stuck behind anything if it drops though a hole and starts rolling back to the exit
  - You need to have enough space for the table to swing through both axes, plus clearance for the servos.  Ideally you also need enough clearance to put the maze base back on, and remember that the base is not level - it slopes so the ball rolls back out the exit hole when it drops
  - You need to consider where to put your springs and how they will be attached.  Springs are not critical, but they are a very good idea if you want your servos to last.  Most cheap servos have nylon gears that are easily stripped by sudden external forces to the servo arm.
 - One servo will have to be mounted on the casing, this will control the ring in one axis.  The other servo will actually be attached to the "ring" (it moves when the other servo moves), and this controls the table top tilt in the other axis (which is always relative to the ring).
 - Consider what orientation works best - the servo arm can be adjusted, so you may want to flip or rotate them to find the best position.

For these reasons, I decided to put my servos on the opposite side of the maze to the exit hole as shown.  There's not quite enough clearance there to replace the sloping base panel, but I've decided not to for now.  If I did, only one servo screw would be in the way and a small cutout of the base panel would suffice.

Spring shape, size and placement
My springs came from wiper blades - some blades are reinforced with flat stainless steel rods and these make a perfect springy lever for attaching servos to the board.  You will have to experiment a bit with size and shape, and consider where they might be placed.  Here are some pointers:

-  Add a 90° twist near the top end of the spring, this increases the strength of the spring and ensures the servo linkage can be attached.
- The springs should be soft (ie. long) enough to provide the servos with some protection. With a servo arm screwed onto the servo pivot point, you can test this by cutting a length of metal and using it to (very gently) try and turn the servo arm at the furthest point from the pivot.  Ideally you should probably have about 10-15mm of flex in either direction without the servo arm moving.  Be careful when doing this, as some servos don't take external forces well and this could strip the gears.
- The springs should be stiff (ie. short) enough to move the table with very little flexing.  This probably comes down to adequate lubrication, but you can test this by taking the same piece of metal above and (with the maze the right way up) using it to tilt the the table in each axis.  There should be no more than a few mm of flexing - any more and your maze will be "sticky" and very hard to play.  You may need to cut the spring shorter, bearing in mind that it will provide less protection for the servos the shorter it gets.
- The springs also allow you to raise the pivot point away from the table - you need some separation to ensure the the spring has room to flex and the table has room to move through the full swing (or at least as much as the servos will allow).

Shape is less important, but with springs like this it is the total length from mounting point to lever arm pivot that gives it its "spring".  You may need to make the springs a little wavy as I have to get the springiness in the space you require.  You may want to try temporarily sticking the servos in place with a tiny dot of hot glue, double-sided tape, Blu-Tack or plasticine.  Watch how each spring moves in relation to the servo arm when the table is tilted in each axis, and look for a good place to mount the spring.  Mark it with pencil.

Each spring will need a small hole at the top end to connect the servo linkage to, plus it may need 2 more at the base as I did depending on how you decide to mount them.  Stainless steel does not drill well at small diameters, so I used a diamond-tipped engraving bit to slowly drill my holes (approx 1mm dia), a drill press will work best for this.  Be patient, you don't want to wear through the diamond coating by pushing too hard, and remember that you want to make the hole a snug fit for your linkage, so keep checking to make sure you don't make it too big.  Don't mount them just yet, but for mounting the springs to the board you could drill two more holes in the base of the spring and use small screws or miniature nails to attach it into the board.

If you find drilling the stainless is too hard, you may wish to use epoxy glue or similar to mount them instead, and on the top end you could glue a small piece of plastic with the hole for the servo linkage instead.

Cable placement
Like the servos, you don't want the cables interfering with the ball or table movement.  Decide where you are going to locate the cables - if the servos are apart from each other you may need additional connectors or extensions.  Don't drill or cut anything just yet until you actually have your servos in place.

Step 7: The Maze Hardware - Putting it Together

Mounting Servos
Using the sliders on the DemoKit app, move each servo as close as possible to the midpoint of its 180° rotation, then disconnect from the board.  Holding the first servo roughly in its mounting position, attach the plastic lever arm to the servo pivot so that it's roughly horizontal.  Screw the lever arm to the servo pivot.  Repeat with the other servo in its place.

Now mount the servos in place.  I used thin strips of sheet metal cut to size as straps around the servos and screwed them into the wood.  In my case the "outer" servo is mounted to the casing near the corner, and it is used to tilt the ring.  The "inner" servo is mounted on a block of wood which is mounted to the ring, close to the ring's pivot with the outside casing.  This servo is used to tilt the inner maze table.

If you are mounting a servo on a block of wood for clearance as I have done, make sure when this block and servo are mounted that there is enough clearance for the maze table to move full swing in both directions, as well as pivot on the opposite axis without hitting anything.

Once you've mounted the servos, you'll need to identify the relationship between servo arm swing and the displacement of the maze table (via the spring). Image 2 depicts the servo arm swing (most servos turn 180 degrees, I allow for slightly less). A full clockwise rotation pushes the spring "down" (at least from this perspective), while a full counter-clockwise rotation pulls the spring "up" approximately the same distance.

Remember the arm linkage (paperclip wire) remains the same length and the spring will only move in one dimension, up or down, so this linkage works a little like an engine crank.  An even up and down movement is now dependent on just the linkage length and position of the spring.

Mounting the springs
Now you can mount the springs.  If you didn't drill the holes in the springs, find the optimum position and glue in place.  If you managed to drill the holes in the base of the springs, you can now position them one at a time, mark and pre-drill the holes slightly undersize with a Dremel and perhaps 1mm drill bit.  You can then use small tacks or 1.5mm diameter nails which have been cut down to approximately 10mm long and re-sharpened on a bench grinder. A small tack hammer works well here.  If drilling/nailing make sure you're nailing into some wood on the other side, not just through the maze surface!

Adding linkage
Now that servos and springs are in place (and assuming servos are still center-swing), with the table level you can start preparing the linkage.  Put a small Z-shaped bend in the wire close to one end and feed this through the hole in the spring.  Measure or mark where on the wire the server arm hole is, then make another Z bend in the wire at that position and cut just marginally after the second bend, as shown in the third image.  You should now be able to feed the bottom Z-bend into the spring and with only slight bending you should be able to gently click the top into place on the servo arm.  Repeat with the other servo linkage.

Wiring it up
Finally, you need to add the wiring.  I used a USB cable that is often found inside PC's to connect the motherboard to a USB port panel (See Image 4).  This works well because at least one end is wired with a block connector which will fit onto the ADK board.  You can carefully trim the plug (usually 8-10 pin) down to 6 pins with a craft knife, and trim the unused wires back.

Bring the servo plugs together and this is where you can drill a hole to feed the cable through.  Drill a hole the same diameter as the cable, cut any plug from the other end of the cable, and feed it through the hole, with the female box connector on the outside as shown in Image 5.

On the other end (the inside), we actually want a male 6-pin block connector to plug the servos into, that is if you don't fancy cutting off the servo plugs and soldering them to this cable.  These can be found on old computer parts, motherboards, all over the place - they are used for most jumper pins and many cable connectors..  I used one from an old sound card.  Solder it on, being very careful to get the wiring of the pins right so that they match the female plug on the other end.  Test with a multimeter if necessary.

I then used a couple of cable ties to hold the wires out of the way of the ball and stop the cable slipping and damaging things if it was tugged from the outside.  I plugged the servos into the male connectors, I then separated the servo plugs and bent the two sets of 3 pins apart so that there was minimal pulling on the relatively fragile servo wires (see Image 1).

Finally, check and double check the servo cable wiring and polarity, then plug the cable into the ADK board.  You should hear the servos move into place if they've been moved off center at all (and hopefully the maze table will move too), and that means you're good to move on to the next step.

Step 8: Fine tuning

Wow - you now have a fully functional maze that you can control from your phone... but chances are that it's not quite playable yet.

Axis swapping
The first thing to adjust is if the axes are the wrong way around.  If your maze moves side-to-side when you tilt your phone forward and back then that's a simple fix - swap the servo plugs over.

(Note to the lazy)
If you've just got the RealMaze APK and skipped "roll your own" in steps 2-5 then the remainder of this step won't apply and unless your setup is exactly like mine you might find yourself with a maze that's difficult to control... You were warned.  It's not too late to go back and install the necessary bits :)

Inverting an axis
If, for example, you tilt your phone forward and the maze tilts back then you need to invert the movement on one axis (or both).  This is done by making a change in the RealMaze code in Ecplise.  Open RealMazeActivity.java from the Package Explorer > RealMaze > src > com.google.android.RealMaze .  Edit the lines highlighted in Image 1 (about line 110) by changing the (x*1.5) to (x*-1.5) if you believe the x axis needs flipping, or change the (y*1.0) to (1*-1.0) if the y axis needs flipping.

Changing sensitivity
If the servos are moving too wildly or not wildly enough for you, then you can change the multiplier on the commands sent to the servos.  For some reason the x axis needed multiplying by 1.5 for me(which is pretty significant - I still don't know why), but it may be dependent on hardware.  Simply adjust the 1.5 or 1.0 in those same two lines to adjust sensitivity.  You probably won't have to change either one lower than about 0.7 or higher than about 2.0.

Recompile, redeploy and retest.  Rinse, repeat.  When it's working better, move to the final (and most important) step....

Step 9: Play!

Fire up RealMaze again, connect to the ADK board, and enjoy the fruits of your hard work!
Read More