Category Archives: Arduino

Anatomy of a Robot

A while back, I wrote a blog post about spherical robots.   I had taken it upon myself to learn a bit more about robotics with the intention of building a simple autonomous robot.  Well, over two years later, I’m at a point where I can do some actual robotics work.  I look back on what I’ve learned… and the rabbit hole of a trek that led me here.

The Coursera Rabbit Hole

mindstormbrick

What goes into a robot?  Well, naively I thought that you hook up servos and sensors tosome kind of micro controller and away you go.  It’s the Lego Mindstorms version of Robotics.  Of course, that *IS* one way to look at robots… but really, that’s just the beginning… the “Hello World” program of building robots.  I wanted to build something a little more sophisticated than the “recommended age 12-adult” crowd.

itunes-artworkWell, for the answer we look to the Control of Mobile Robots class offered on Coursera.  In this class, Dr. Magnus Egerstedt introduces Control Systems.  The class itself does not get into the hardware of building robots, but digs into the abstraction layers necessary for successfully modeling and controlling things that interact with the real world. 

What exactly do I mean when I say “Control things?” Well, think about yourself for a moment.  If you’re standing and someone shoves you, you are able to react in a way to keep yourself stable and standing… or simply put you’re in control of your body.  The act of keeping yourself upright is a complex set of muscle movements that need to be carried out correctly but you don’t need to think about how to control each muscle… you just do it.  The instinctive impulse to lean or step is handled by your innate control system.

itunes-artworkIt’s not enough, however, for a robot to be “controllable”.  My goal is to build a robot that’s autonomous.   That requires some form of higher level artificial intelligence.  It turns out that Coursera offers another class geared toward exactly this: Artificial Intelligence Planning!  In this class, Dr. Gerhard Wickler and Professor Austin Tate take you through a survey of programmatic problem solving algorithms.  I was amused to learn that like all other computer science problem, artificial intelligence problem solving comes down to a search algorithm.

At the end of this course, you’ll be able to write a program that given some set of circumstances and corresponding set of possible actions, it will figure out what to do to accomplish its goals; assuming that some possible set of actions can achieve the goal.

small-icon.hoverThis lead me to the next problem… perception.  An autonomous robot has sensors and it needs to be able to figure out some “state” of the universe in order for it to use its problem solving capabilities.  How on earth do you map images/sounds/echolocation to logical states of the universe?  Through machine learning.  As it turns out, Coursera offers a LOT of classes on exactly this.  The most notable of these classes is Coursera’s co-founder‘s class on Machine learning…  Here, you learn all kinds of algorithms for automatically classifying and identifying logical states based on noisy or confusing input.

itunes-artworkA more advanced class that I really enjoyed focused on state of the art Neural Networks.  The class is called Neural Networks for Machine Learning and is taught by Dr. Geoffrey Hinton.  This class goes into great depth on various kinds of Neural Networks.  This class totally blew my mind.  I have no doubt that the correct application of neural nets with the right kind of self-motivating planner will lead to formidable AIs.

Putting it all together

First let’s talk about hardware.  Below is a list of hardware that I’m going to use and I’ll parallel it with what I feel may be the human anatomy counter-part.

IMG_0465I’m going to use an Arduino Uno as the primary interface with all of my robot’s actuators.  It represents the spinal cord and instinctive nervous system of the robot.   The Arduino is a very simple microcontroller that isn’t terribly fast.  It also doesn’t have much in the way of memory.  It does have extremely easy interfaces with motors and sensors.  This makes it ideal for running a closed loop System. (See Control of Mobile Robots class for details).

raspberrypiConnected to the Arduino will be a Raspberry Pi. The Pi will be the brains of the Robot. All higher order problem solving will occur here.  The brain and the spinal cord will talk to each other using SPI.  Naturally the Raspberry Pi will be the master of the SPI bus.  As the robot gets more complex, it might be necessary to attach more than one microcontroller (maybe not all arduinos)… especially if I start working with more complex sensors.

shapelockThe supports and overall skeleton of my robot will be created with Shape Lock.  It’s a material that can be melted, shaped and re-used over and over.  It claims to be machinable (using my dremmel) and durable.  I imagine that if I need stronger load bearing parts, I can prototype in shape lock and carve some other material based on the prototype.  Wood is a likely candidate.

Okay. The big pieces are out of the way.  Now the fun stuff.  What sensors / servos will I use?  I have a variety of electric motors, solenoids and steppers that I picked up from Adafruit. It’s likely that my first robot will be a simple differential drive deal.. but eventually I’d like to go back to my ideas in the original blog post and create a spherical robot.   In the end, the actual drive system and sensors don’t matter that much… they’re just the accessories of the Mr. Potato head.  All interchangeable.

SparkFun Color LCD Shield – First Impressions

I picked up a SparkFun Color LCD Shield while I was shopping for some sensors and battery packs.  I thought that maybe I could use it to help visualize sensor data prior to passing it off to my Raspberry Pi.

The shield itself didn’t come with headers… which is okay, because I had a few extra from a purchase I made from adafruit. A short solder job later, It’s plugged into my Uno.

I grabbed the Arduino library from github, plugged it in and tried to run the examples.  Initially, the board didn’t seem to function, but after reading the documentation a little more, I realized that sparkfun ships one of two different models. I happened to get one that didn’t run with the default code. The change to the examples is extremely trivial.  You change the following line:

lcd.init(EPSON);

to

lcd.init(PHILLIPS);

One thing that I noticed about the shield… the updating is very slow, so you have to be extremely mindful of how you want to change your pixels. Simply clearing the display has a visible redraw. I wrote a short program to play around with the buttons on the shield. Essentially, it just draws or undraws rectangles based on whether or not buttons are pressed. Here’s the code itself.  If you try it out, you can see what I mean about the redraw rate.  Either this is an artifact of the sparkfun library or it’s a limitation of the device itself. I guess I can look at the library and see if there’s anything obvious.

#include <ColorLCDShield.h>
LCDShield lcd;

byte cont = 40;  // Good center value for contrast
int lastS1 = 0;
int lastS2 = 0;
int lastS3 = 0;

void setup() {
  pinMode(3, INPUT);
  digitalWrite(3, HIGH);
  pinMode(4, INPUT);
  digitalWrite(4, HIGH);
  pinMode(5, INPUT);
  digitalWrite(5, HIGH);

  lcd.init(PHILLIPS);  
  lcd.contrast(cont);
}

void loop() {
  int s1 = digitalRead(3);
  int s2 = digitalRead(4);
  int s3 = digitalRead(5);

  if (s1 == lastS1 && s2 == lastS2 && s3 == lastS3) {
      return;
  }

  if (s1 != lastS1) {
    if (s1) {
      lcd.setRect(80, 35, 131, 51, 1, WHITE);
    } else {
      lcd.setRect(80, 35, 131, 51, 1, CYAN);
    }
    lastS1 = s1;
  }

  if (s2 != lastS2) {
    if (s2) {
      lcd.setRect(80, 67, 131, 83, 1, WHITE);
    } else {
      lcd.setRect(80, 67, 131, 83, 1, MAGENTA);
    }
    lastS2 = s2;
  }

  if (s3 != lastS3) {
    if (s3) {
      lcd.setRect(80, 99, 131, 115, 1, WHITE);
    } else {
      lcd.setRect(80, 99, 131, 115, 1, BLUE);
    }
    lastS3 = s3;
  }
}

8×8 LED Matrix animation

It’s been a little while since I messed with my Arduino… so here we go.

This time around, I hooked up with an 8×8 LED matrix. Essentially, it’s an array of 64 LEDs addressable via 16 pins.

But wait, you ask… how can you address 64 pins with only 16 pins?? That’s an excellent question!  The answer is… not very well.  It turns out that you can only independently address one LED at a time with this system… well, really only one row at a time… otherwise you get unexpected LEDs lighting up.

The answer to this problem is essentially rastering.  Essentially this means that you display one row at a time.  You just make sure that the rate at which you display rows happens fast enough that the observer can’t see that you’re only ever have a single row illuminated.

I chose a really boring animation here.  It’s just an inverting rectangular region inverting itself.  This project was taken almost verbatim from project 19 in Michael McRoberts’s Beginning Arduino.

To the right, you see an animation of my LED Matrix. Kinda distracting, huh… sorry.

A bit later, I’ll use this LED matrix as a means of outputting an accelerometer.  I’d like to think that I can come up with some cool looking UI in 64 LEDs.

For the curious, here’s the code listing for this project:

#include <TimerOne.h>

const int gLatchPin = 11;
const int gClockPin = 13;
const int gDataPin = 12;

const int pLatchPin = 8;
const int pClockPin = 10;
const int pDataPin = 9;

int n = 0;

int icons[2][8] = {
    { 
      0B11111111,
      0B11111111,
      0B11000011,
      0B11000011,
      0B11000011,
      0B11000011,
      0B11111111,
      0B11111111,
    },
    {
      0B00000000,
      0B00000000,
      0B00111100,
      0B00111100,
      0B00111100,
      0B00111100,
      0B00000000,
      0B00000000,
    }
};

void setup() {
    pinMode(pLatchPin, OUTPUT); 
    pinMode(pClockPin, OUTPUT); 
    pinMode(pDataPin, OUTPUT); 

    pinMode(gLatchPin, OUTPUT); 
    pinMode(gClockPin, OUTPUT); 
    pinMode(gDataPin, OUTPUT);

    registerWrite(gLatchPin, gClockPin, gDataPin, 0B00000000);
    Timer1.initialize(10000);
    Timer1.attachInterrupt(matrixUpdate);
}

void matrixUpdate() {
    for(int i = 0; i < 8; i++) {
         registerWrite(pLatchPin, pClockPin, pDataPin, 1 << i);
         registerWrite(gLatchPin, gClockPin, gDataPin, icons[n][i]);
    }
}

void loop() {
    n = 1 - n;
    delay(1000);
}

void registerWrite(int latchPin, int clockPin, int dataPin, byte data) {
     digitalWrite(latchPin, LOW);
     shiftOut(dataPin, clockPin, MSBFIRST, data);
     digitalWrite(latchPin, HIGH);
}

You can see from the code listing, (and probably from the image as well) that I ended up using two 8-bit latches.  I could have used less pins and cascaded the latches into a single 16-pin logical latch… but I didn’t out of lazyness.

The other thing of note in this code listing is the TimeOne library.  I had to grab it from the google code project. I was pretty surprised that you could schedule an interrupt driven timer at microsecond granularity.  Pretty amazing.

Arduino Control from Web via WiFly

I bought a WiFly a while back but didn’t really do much with it.  For those of you not in the know, a WiFly is a compact wireless device that you can buy on a little break-out board… or in this case, on an Arduino Shield.

The interface to the WiFly is pretty straight forward.  You initialize the library then create a Client object.  This Client object has typical filehandle-like methods such as read(), available(), println() etc.

In this example, I took my previous setup with 8-bit latches and used the LEDs to display output that I submitted to a webservice using the WiFly.  The Webservice in question is a very simple php app that returns a single 8-bit hex number.  Here’s the code:

<?php print '@'.dechex(time() % 255); ?>

The prepended ‘@’ sign is a flag value.  Because read() returns just a single char, I wanted to skip through all of the http header information to the data.  I stop when I encounter the first ‘@’.

I modified the latch setup I had by using two triplets of pins instead of sharing the single triple.  This allowed me to independently control two latches. Here’s the final code for the project:

#include "WiFly.h"

int latchPin1 = 2;
int clockPin1 = 3;
int dataPin1 = 4;

int latchPin2 = 5;
int clockPin2 = 6;
int dataPin2 = 7;

Client client("www.tokyo3.com", 80);

void setup() {
  Serial.begin(9600);
  pinMode(latchPin1, OUTPUT);
  pinMode(clockPin1, OUTPUT);
  pinMode(dataPin1, OUTPUT);

  pinMode(latchPin2, OUTPUT);
  pinMode(clockPin2, OUTPUT);
  pinMode(dataPin2, OUTPUT);

  WiFly.begin();

  if (!WiFly.join("ssid", "password")) {
    Serial.println("Association failed.");
    while (1) {
      // Hang on failure.
    }
  }
}

int convert(char ch) {
    if (ch >= '0' && ch <= '9') {
         return ch - '0';
    }
    if (ch >= 'a' && ch <= 'f') {
         return ch - 'a' + 10;
    }
    return 0;   
}

int getWebValue() {
  if (!client.connected()) {
      Serial.println("Connecting...");
      if (!client.connect()) {
        return 0;
      }
  }

  client.println("GET /arduino.php HTTP/1.1");
  client.println("Host: www.tokyo3.com");
  client.println();  

  char ch;
  while (client.available()) {
    ch = client.read();
    Serial.print(ch);
    if (ch == '@') {
      break;
    }
  }

  if (!client.available()) {
     return 0;
  }

  int a = convert(client.read());
  int b = convert(client.read());

  return (a << 4) + b;
}

int count = 0;
void loop() {
    int a = getWebValue();

    if (count++ % 2 == 0) {
        digitalWrite(latchPin1, LOW);
        shiftOut(dataPin1, clockPin1, MSBFIRST, a);  
        digitalWrite(latchPin1, HIGH);
    } else {
        digitalWrite(latchPin2, LOW);
        shiftOut(dataPin2, clockPin2, MSBFIRST, a);  
        digitalWrite(latchPin2, HIGH);
    }
    delay(1000);
}

Pretty simple for the most part.  As with the WiFly examples, I use the Serial Monitor to echo print.  Very useful when trying to figure out what you’re getting via network.

 

Monkeying with 8-bit Latches

I while back, I bought a couple of 8-bit Latches which I had intended to conquer the world with… but just never got around to it. As I’ve just found out… these specifically may not be the right model for that purpose. sigh.  Let me expound…

As I’ve explored in previous Arduino setups, I want to control lots of things with few output pins.  With this specific setup, I was hoping to populate two different 8-pin latches using a large number of shared pins like with the LCD project… but alas, these latches don’t really like sharing their pins…

If I share pins between the latches (clock/latch pins) but have a selectable data pin, the unselected latch still *thinks* I’m talking to it… What I need is a latch with an Enable Pin.

Pictured above, I was just testing to verify that both latches actually worked. Both are connected to the same outputs, so their values are mirrored. I won’t post any code this time because I used the ShiftOut example verbatim.

Chaining Demultiplexers

Before, I controlled 6 LEDs with 3 pins.  This fit very neatly onto a single 3-8 Demultiplexer.  For me to achieve my goals of world domination, I need to be able to chain them.

What exactly do I mean by chaining?  Well, by themselves, a 3-8 demultiplexer can control 8 things with 3 control pins.  It follows, that to control 16 things, we need 2 demultiplexers and 6 control pins.  Well, by chaining, you can control 16 things with just 4 pins!  Well, how does this work?

Well, you take the regular 3 control pins and connect them to BOTH multiplexer input pins. The 4th “input” pin actually just switches between which demultiplexer we’re using.  So it connects to the “G1″ of the second and one of the G2s on the first.

I couldn’t really do this before because I lacked the space on my previous little breadboard.  In case you hadn’t noticed… I’ve upgraded!

WyFly Shield off to a rough start

Here you see my new WyFly shield!  This little guy will one day bring Wifi capabilities to my Arduino… but not yet… not yet.

Thankfully there isn’t a lot of assembly required for the shield.  All you have to do is solder in the headers… which is easy enough… even for me! (see the evidence)

Out of the box, the libaries didn’t seem to want to work.  First there’s the “no such WProgram.h” issue which is easy enough to solve… you change the #include to “Arduino.h”.. but then there were some strange Arduino API changes with the Print object.  Nothing was terribly wrong… the write() methods now returned a size_t when before they were void.

Compilation out of the way… I uploaded an example… and nothing happened. I was supposed to see a google search result for “Arduino” scroll past on the Serial Monitor… but nothing.  Looks like more digging for me.

Controlling multiple LCDs from one Arduino

Taking the previous Arduino project a step further, I managed to get two LCDs independently updating from a single Arduino.  My original plan was to have 4 of them updating independently, but two of the cables that I made for connecting the LCDs to my breadboard somehow stopped working.  I suspect that 14-pin header stopped making contact with one or more of its pins.

You can see in the image to the right, how I constructed this cable.  It’s essentially a ribbon cable that I cut down 14-pins wide.  On one end I connected the 14-pin header and at the other, I connected a series of Molex connectors.  I chose the to break the wire into three groups of four pins plus a single group of two.  The group of two corresponds to the Power and Ground of the LCD.  The first group of 4 has the LCD’s RW, RS, Enable, and Contrast pins.  The final two groups of four end up being the data pins. (In four pin mode, only the second group of data pins are used).

If you look at the assembly from above, you can see that on the larger breadboard, I have a similar setup to my previous project’s setup.  Essentially, I have a 3-8 Demultiplexer and a Hex inverter.  The input to the Demultiplexer comes from the digital out pins from the Arduino and the outputs run through inverters.  I connect the inverted values to the “G1″ of the LCD which, when set to LOW disables writing to the LCD.  Since I know that the inverted output of the demuxer will only ever have a single line set HIGH, I can use it to select which LCD to enable.  The other LCD pins are all connected in parallel to the controlling pins on the Arduino.

#include <LiquidCrystal.h>

LiquidCrystal lcd(11, 9, 5, 4, 3, 2);
int state;

void setup() {
  pinMode(12, OUTPUT);
  pinMode(10, OUTPUT);

  // Pin 6 controls which LCD. If I had more than
  // two LCDs, I would need more pins to select them
  pinMode(6, OUTPUT); 

  state = 0; // Pin 6's value 0 -> LOW, 1 -> HIGH

  // Initialize the first LCD
  digitalWrite(6, LOW);
  lcd.begin(20, 2);
  lcd.print("I am Tweedle Dee!");

  // Select and initialize the 2nd LCD
  digitalWrite(6, HIGH);
  lcd.begin(20, 2);
  lcd.print("I am Tweedle Dum!");
}

void loop() {
  digitalWrite(6, state == 0 ? LOW : HIGH);
  lcd.setCursor(0, 1);
  lcd.print(millis()/1000);
  delay(1000);

  state = 1 - state; // toggle which LCD to display on
}

The program itself was based heavily on the LCD Hello World example.  I changed a couple of pins around to be more convenient for my wiring… but the loop() function was copied almost verbatim.  The intent of the program was to have one LCD display “I am Tweedle Dee!” and the other to display “I am Tweedle Dum!” then Tweedle Dee will start counting all even numbers while Tweedle Dum counts all odd numbers.  As you can see here… it worked out fairly well!

Controlling 6 LEDs with only 3 pins

The Arduino Uno has something like 13 digital I/O pins and 5 analog I/O pins which can be re-tasked to act like digital pins bringing the grand total of 18 possible Digital I/O pins to work with… so what happens when you need to work with more than 18 different devices?  For example… what if you wanted to independently strobe 19 LEDs?

Here, I've connected 3 LEDs directly to the Arduino UNO's digital I/O pins 2,3 and 4. In this configuration, I could control at most 18 LEDs independently.

I’ve come up with a project which faces just such a problem… I want to be able to independently light up and update 32+ little 20×2 LCDs with a single Arduino.  To give a little context, each LCD has 16 pins, 8 of which are data pins.   This means that 8 of the 18 digital out pins from the Arduino must be used for sending data to the LCD.  That hardly seems like more than one could possibly be driven by a single Arduino!  Clearly, if my plan is to be realized, I need to come up with a scheme that doesn’t involve directly driving all the LCDs from the Digital I/O pins.

Remembering back to my Structural Computer Organization class, I realized the answer: Demultiplexing.

Here, I'm controlling 6 LEDs with only 3 pins through a 3-8 multiplexer. Chaining multiplexers together, I could control 2^N LEDs with N pins.

A Demultiplexer or Decoder is a component made up of logic gates that takes a combination of inputs and chooses a corresponding output.  Generally, for you can choose from 2^N outputs with N inputs.  Learning about them in class is one thing.. but actually sticking them on a breadboard is another.  I chose this Demultiplexer: the HD74LS138P.  It’s a 3-input 8-output multiplexer. It turns out, though that it works counter to how I expected it to.. instead of the selected output being high, the selected output was low and the other outputs were high.  When I hooked it up to my LEDs… all of the LEDs were on except for the one currently being selected!

Using a hex inverter, I was able to invert the outputs of the Decoder and make the selected output be on while having the other outputs stay off.

Ok… well, If I want the unselected outputs to be low while the selected is high, I need to invert the output of the multiplexer.  It turns out that there are little chips that have a bunch of inverters built into them.  The popular form factor seems to be the “Hex Inverter” which is simply 6 inverters crammed into a 14-pin package.  I ended up using a MC54F04 to do it. It seems like every semiconductor makes identical hex inverters, so Jameco‘s catalog just says “popular manufacturer”.  Anyhow, you can see from the photo to the left, using the inverters, we now have selected output being on and unselected outputs being off.

If you’re curious about the code that I used for this setup? Here it is.. It’s pretty simple:

int count = 0;
int values[8][3] = {
   { LOW, LOW, LOW },  
   { LOW, LOW, HIGH },  
   { LOW, HIGH, LOW },  
   { LOW, HIGH, HIGH },  
   { HIGH, LOW, LOW },  
   { HIGH, LOW, HIGH },  
   { HIGH, HIGH, LOW },  
   { HIGH, HIGH, HIGH },
};

void setup() {                
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);     
  pinMode(4, OUTPUT);       
}

void loop() {
  count = (count + 1) % 8;
  digitalWrite(2, values[count][0]);
  digitalWrite(3, values[count][1]);
  digitalWrite(4, values[count][2]);
  delay(1000);
}

In the setup method, we say that pins 2, 3, and 4 are assigned output roles.  In the loop, we increment our count variable and if the count exceeds 7, it gets set back to 0.  We then set our pins HIGH or LOW depending on the count’s offset in our table of values.   We also put a 1 second delay between loop executions so that the loop doesn’t happen too quickly to see.

One kind of annoying problem that I ran into while stringing up my Decoder was, it has 3 pins called G1, G2a and G2b which are effectively enable pins.  G1 must be HIGH and BOTH G2a and G2b must be ACTIVELY LOW in order for the demultiplexer to work.  I didn’t realize it and only connected G2a to ground… so naturally nothing worked because G2b was not actively being set to LOW (not directly connected to ground).  It wasn’t until I grounded both pins, that the decoder started decoding.

16×2 LCD Display Contrast

A few weeks ago, I put in an order to Jameco for some parts that’ll help me complete some of the projects in Michael McRoberts‘s book Beginning Arduino.

One of the more interesting components was this KST1602B 16×2 LCD Display.  I dunno about you all, but ever since I saw one on a digital calculator, I’ve wanted to bend one of these bad boys to my will… and now I have! … well, sorta.

The first time I wired this up, I got a totally blank screen. I had assumed that I did *something* wrong and went through and re-verified that things were connected right.  Finally, I eyed the resistor that I had been using on the “Contrast” pin on the LCD.  (V0 in the case of this one).  I had chosen a resistor close to that described in the book, but meh… so I pulled out the potentiometer from my last project and hooked that up to pin V0.  It turns out that the resistance needs to be a lot more than what I had expected!

To the left you can see an image with three contrast settings on the potentiometer.  The top one is max (about 10k ohms) the middle one was maybe 8k ohms and the last one represents anything less than say, 7k ohms.

When you look at the data sheet PDF, the section called “Adjusting Display Contrast” seems to suggest that you can put a resistance of between 20 and 50k ohms… that’s a HUGE range considering that what you can go from visible to NO contrast in less than 2k ohms.  I feel like the contrast range should be a little more linear… but that’s just me.