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.

 

Terrain Tiles

The challenge here is, What is the minimal set of terrain tile types to be able to build arbitrary terrain in a side scroller?  In theory, you don’t need minimal sets of anything if your blocks fit exactly into a square.  You see that all over; especially in the older Nintendo classics.  I want to be able to use a more diverse set of borders though… and I *think* the above image represents a complete set.

That’s not to say that each type of tile won’t have many distinct tilesets… Hopefully I will have quite a few distinct tilesets for this game.

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.

Building for Windows!

Download the Windows Version!

It took me a while to get there, but I’ve finally gotten a Windows build of the Weirdo in a Weird Land bootstrap project!

My first attempt at building one involved grabbing Visual Studio 10 Express but it really wasn’t meant to be used from the command line… at least not easily…

The successful strategy was to use the Minimalist GNU for Windows toolchain.  This lead to some heartache which began with linker issues… but working with the SDL FAQ, I got things mostly working.  Of all the problems, the most surprising to me was the fact that including libraries in gcc is significant.  Specifically… the following did not work:

$(CC) -o $(BUILDDIR)/$(EXETARGET) $(BUILDDIR)/main.o \
    $(BUILDDIR)/Level.o $(BUILDDIR)/SDLAppMain.o \
    -L$(SDLDIR)/lib -L$(SDLIMAGEDIR)/lib/$(ARCH) \
    -lSDLmain -lSDL -lSDL_image -lmingw32 -mwindows

but THIS did!

$(CC) -o $(BUILDDIR)/$(EXETARGET) $(BUILDDIR)/main.o \
    $(BUILDDIR)/Level.o $(BUILDDIR)/SDLAppMain.o \
    -L$(SDLDIR)/lib -L$(SDLIMAGEDIR)/lib/$(ARCH) \
    -lmingw32 -lSDLmain -lSDL -lSDL_image -mwindows

The significant part here is the -lmingw32 being first.  Without that, I got the following linker issue…

Undefined reference to 'WinMain@16'

Which is discussed in the FAQ… but the answer did not point out that the ordering of the libraries was significant!

Now i just need to create a proper Makefile that will switch easily between the two architectures…. then it’s time to actually write the game!

UPDATE: The original zip that I uploaded seemed to be missing a few necessary files… specifically two DLLs: libgcc_s_dw2-1.dll and libstdc++-6.dll both of which are now part of the distribution.

Weirdo in a Weird Land

Weirdo in a Weird Land is the working title for the slowly progressing game.

It took a while to actually get the application bundle squared away.

Click Image to Download v0.0.1!

One of the more irritating parts of creating the bundle was referencing the image resources.  Mac Applications are supposed to keep their data in a Contents/Resources but using the provided SDLMain, your application’s working directory is the PARENT of the resource bundle… so you’d have to make the assumption that the end user didn’t rename the application bundle on you and build your path including what you think your resource bundle is named.

I modified the SDLMain a little bit, putting the working directory at the top level of the Application Bundle.  This allows me to reference my image files as: Contents/Resources/Images/ which is still a little ugly, but probably more reliable.  The “correct” thing to do would be to have SDLMain expose a method which allows me to retrieve the path of individual resources.  That’s probably a much later change though.

My most recent efforts are to get a Windows build going.  I’d like to do the up front work to make this game cross platform.  This way, I can release builds for both Mac and PC/Win32 relatively easily in the future.  My first attempt at creating a Win32 build was using Visual Studio 2010 Express, but I ran into a lot of strange linking issues.  The compilation process was tough too.  cl.exe command line compiler had radically different invocations than gcc… so it’s unlikely that I’d be able to reuse the same Makefile. There has to be an easier way to build a windows app than this…

The SDL Tutorial suggests using mingw32 which is a minimalist windows toolchain built on top of all GNU tools.  This means that I *SHOULD* be able to reuse my Makefile and if it’s part of the tutorial… I shouldn’t run into weird issues.  We’ll see how that pans out.  Hopefully by Thursday I’ll have a slightly expanded build that runs on both Windows and OSX!

SDL side scroller takes shape

 In my previous post on SDL, I talked a little bit about layering bitmaps to create a simple side scroller.

Here, I’ve actually gotten bitmap layering to work.  I’ve used the rough bitmaps that I drew for the last blog post and built some code around it.   I haven’t gotten to the point where I can built a distributable binary yet, but I’m hoping that it won’t be too tough.  I’m hoping to NOT have to involve xcode… but all literature I’ve found on building apple distributables seem to center around that tool.

Here’s a screenshot of the resulting app.  Doesn’t look very different from my mockup… but that’s probably a good thing.

The way this ended up being implemented was through a Level class.  The Level class has an array of Layers and a current position (x axis).  Each layer has a coefficient that describes its motion relative to the Level’s x position. Foreground objects have a coefficient of > 1 and objects further in the background have coefficients less than one.

Each Layer has an array of LayerObjects. Each LayerObject which includes a bitmap and a coordinate. They’re arranged in the Array in increasing order of x.

I captured the SDLK_LEFT and SDLK_RIGHT key events.  When SDLK_RIGHT is pushed, I’d increment the level’s x position until the key was released.  Similarly for the SDLK_LEFT button except the position is decremented.

 

 

 

 

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!

PGM Class and Octave

About a month and a half ago, I signed up for an on-line class called Probabilistic Graphical Models in an attempt to learn a bit more about some of the math that we use at Topsy Labs.

The strange logo to the right is the Octave logo.  To quote the Octave website…

GNU Octave is a high-level interpreted language, primarily intended for numerical computations. It provides capabilities for the numerical solution of linear and nonlinear problems, and for performing other numerical experiments.

Based on that description, it makes sense that this and Matlab are the two languages recommended for this course.  Yeah. This means that I’ll be learning yet another language… but I’m hoping that octave will allow me to quickly generate cool visualizations for large data sets if not directly, then through gnuplot.