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!

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.

 

Smooth Analog Input Class for Arduino

In the above photo, you see my Arduino Uno with a mini-breadboard ProtoShield.

Here, I wired it up to accept data from a potentiometer on analog input A0.  I also have a standard servo connected to digital pin 7.  The point of this is, you turn the potentiometer, it produces a corresponding motion in the servo.

Here’s the initial code that I used for making this happen:

#include 

Servo servo;
int last;
void setup() {
    servo.attach(7);
    Serial.begin(9600);
    last = -1;
}

void loop() {
  int current = analogRead(A0);
  int scaled = map(current, 0, 1024, 0, 180);
  if (scaled != last) {
    last = scaled;
    Serial.println(scaled);
    servo.write(scaled);
  }
}

Pretty simple stuff.  You see I attach he Servo object to pin 7 and within the loop() section, read from A0, scale the value, then write it to the servo! It works!

One kind of annoying thing that I noticed was… the input from the potentiometer wasn’t terribly stable.  Even when it was just sitting there, it would output values that were up to plus/minus 5.  Because of this, my servo was constantly twitching.  Not only is that probably not good for the servo, you could constantly hear it too… so it was annoying.

It turns out that in one of the Arduino Tutorials, they talk about analog input smoothing.  Essentially, you take 10 readings and average them.  That’ll give you a more stable value.  The problem with using the code from the tutorial is, it’s ungainly.  It would be nice if we could create an object, attach it to A0 and have it automatically smooth incoming values for us… well, that’s what I wrote!

You can grab the actual code from here: http://github.com/rl337/incubator/tree/master/main/arduino/libraries/SmoothAnalogInput

The prototype for the object looks like this:

#define SMOOTH_ANALOG_INPUT_SIZE 32

class SmoothAnalogInput {
    public:
        SmoothAnalogInput();
        void attach(int pin);
        void scale(int min, int max);
        int read();
        int raw();

};

The object smooths data over 32 samples. You attach() the object to whatever pin you want it to smooth input for, in our case, A0. the raw() method takes a reading and returns the raw value from the analog input. the read() method returns the smoothed result which can be automatically scaled between a min/max value if you call the scale() method. Here’s the program reworked to use the SmoothAnalogInput object

#include 
#include 

Servo servo;
SmoothAnalogInput ai;
int last;
void setup() {
  Serial.begin(9600);
  servo.attach(7);
  ai.attach(A0);
  last = -1;
}

void loop() {
  int sensorReading = ai.read();

  int scaled = map(sensorReading, 0, 1024, 0, 180);
  if (scaled != last) {
    last = scaled;
    Serial.println(scaled);
    servo.write(scaled);
  }
}

Looking at the Serial Monitor, there are still a few cases where the servo fidgets, but by and large, the values become stable quickly after you stop moving the potentiometer.

An Arduino general purpose detector!

I’ve been spending some time getting acquainted with my new Arduino Uno.

I did the first Blinking LED tutorial which went exactly as expected.  This particular board has a built-in LED connected to pin 13, so I didn’t even need to do any wiring!

Having forced the on-board LED to blink, I decided to get a little more ambitious.  Along with my Arduino, I bought a bag of LEDs which came with the appropriate resistors for building simple circuits with the board I have.  I attached a 2nd LED to a small Bread Board and wired it up to pin 12.  After modifying the program a little bit, I got the two LEDs to alternate blinking.

Not wanting to stop at using only 2 LEDs, I strung up 5 more to the Bread Board and connected each to a corresponding pin from 7 to 11.  With everything wired up, I coded up a simple function that would take a number from 0-6 and light up an appropriate number of LEDs.  0 leds if 0 were passed and 6 if six was passed.  You can see that segment of the code here:

void light(int i) {

  if(i < 0) { i = 0; }
  if (i > 6) {  i = 6; }

  for(int j = 0; j < 6; j++) {
     int reg = 12 - j;
     if (j < i) {
        digitalWrite(reg, HIGH);
     } else {
       digitalWrite(reg, LOW);
     }
  }
}

The first time running it, I simply cycled through numbers from 0 to 7 which resulted in the LEDs lighting up one at a time then resetting.

Finally, I decided to mess around with the Arduino’s Analog Input capabilities.  The input seems quite sensitive because as I touched the wire that I connected to the input, it immediately began registering a voltage.   In my program’s main loop, I scaled the analog input to the 0-7 range of my LED array.  Now when I touch the wire, the more fingers I touch the wire with… the more LEDs light up!  Here’s the pic!

Here, I was holding the wire with three fingers; my thumb, pointer  and middle finger… four of the LEDs lit up.  Presumably, if I connect up any random sensor (light, sound, etc), the intensity will light up a corresponding set of LEDs.  That aught to be more useful than detecting fingers touching a wire.

Spherical Robots and Arduino Uno!

Back in November, I was at the Academy of Science for Nightlife and found nestled in the creepy taxidermy (African Hall), I ran into Spherical Robots rolling around. Check out the video:

This particular set of robots were originally created for Burning Man, but it’s no surprise to me that they would tour around the more sciency venues of San Francisco.  I’d never really considered a spherical robot before… but I guess it’s a “thing”.  Go ahead! Google it!

Now to me, the easiest way to get a sphere moving would be to have a rod running through an axis of the ball and you roll around it using either weight or a gyroscope on whatever internal mechanism you’ve got driving.  In this design you effectively have one HUGE wheel. These robots, however did not seem to do that.  They were able to roll in arbitrary directions.  They didn’t have to turn to change direction.

My initial gut feeling was, it used a pair of gyroscopes offset from each other by some angle.  When the orientation of the two gyroscopes change, the sphere’s effective center of gravity would shift causing it to move.  After doing some reading, though, it seems like that is not the case. A more likely scenario is… you have a large pendulum style structure which is moved around with a pair of solenoids.  This apparatus is dangled from a stable platform.  When the pendulum is pushed in a direction by the solenoids, the center of gravity shifts and the ball rolls.  The amount that the pendulum can move the ball is proportional to the weight at the end of the pendulum.

All of this conjecture has lead me to conclude that I need to try it out.  So… I’m off to learn a little bit of robotics.  So… how does one get started in robotics?  One dives right in!

I’ve been wanting to work with the Arduino family of microcontrollers, and this seems like an ideal project.  I ordered myself an Arduino Uno, a couple of add-on boards and am ready to rock!

My first goal will be to familiarize myself with the Arduino programming language and generally make myself comfortable with the tools involved.

There is some soldering involved.  You can see in the above image, my new toys.  The blue circuit board is the actual Arduino itself.  Below the magnifier is an add-on board that will allow me to control two motors.  (some assembly required).   I have a 2nd add-on board coming which will have add a small LCD display. I’m sure that board will be the one I play with the most (At least at first).

Naturally, I had to try to put together the motor controls, but it seems like fate would have other plans… Look at what happened to my soldering pencil:

Yeah. So… a new one is on the way. I guess soldering will have to wait a few days.