DSO nano and synth circuit

A few days ago, a co-worker let me borrow his DSO nano to run a few tests. First thing I decided to do was throw a really chaotic waveform at it. I built this little synth with 2 square wave oscillators.


Square wave oscillator schematic

It is kind of comical to call this a synth or even a set of oscillators. It is basically a simple NOT gate arranged in a feedback loop. The capacitor fills up until it reaches the breakdown voltage of the internal diode in the NOT gate, at that point, the signal is inverted to GND and the capacitor discharges. When it reaches ground, the output signal inverts again and the process starts over. The result is a square wave. The potentiometer controls the amount of current flowing into the capacitor and thus alters the amount of time it takes to fill up. In effect, altering the frequency of the square wave. I built two of these and muxed the signals together with some resistors, kind of like a fixed mixer. The overall signal is pretty hectic, with weird beat frequencies and strange tiny oscillations in the individual frequencies themselves.

I found it pretty hard to get the DSO nano to get a good read on it but it was pretty hard with my regular scope as well. Probably not the best waveform to start with. So, I decided to try out some simpler waveforms. I programmed an Arduino to just spit out ‘a’ on the UART every second and used a rising slope trigger to freeze the waveform. It worked really well for that. It also worked really well for just a square wave generated on the Arduino. It was able to guess the frequency with accuracy. Unfortunately my phone had died at that point and I couldn’t get any pictures or video.

Overall I found it pretty simple to use and a surprising amount of functionality for it’s small size and price. I have to admit though, I wouldn’t find much use for it as I am almost always in front of a desk where I can use my USB scope and software. I think this would be more helpful for someone who works in ‘the field’ so to speak. It is pretty much as good as you are going to get in a pocket-sized package.

Posted in Uncategorized | 1 Comment

RFID <--> Ethernet Shield Client <--> Rails

Last week A few months ago, I wrote an article on connecting the Parallax RFID reader to the the Arduino. The reason I was revisiting that device was because I am working on a system for our hackerspace which will allow people to find out who is in the hackerspace at any given time. The overall system requires the Arduino to connect to the internet as a client and tell the Ruby on Rails application that person with RFID tag XXXXXXXXXX has walked into or left the space. The Rails application will be able to ‘publish’ this information to different mediums [web, twitter, facebook, IRC, etc] by providing a simple API for other programmers in the space to utilize.

The whole system is too complicated to explain right now and I am not finished. I plan on writing my next article about that. For now, I just wanted to document some of the issues I had with the Arduino Ethernet Shield and how I resolved them as it may be of help to others trying to figure it out.

Arduino Ethernet Shield

Arduino Ethernet Shield

The ethernet shield, like the RFID reader, was not as simple to use as I hoped it would be. The information out there was decent, but nothing beyond explaining the examples. First I must explain my use cases to put context to the example code.

My goals for the code are to first send two pieces of information to the Rails application:

  1. A secret API key [to prevent fraud]
  2. The Tag code read by the RFID reader

Then I want to read the response and differentiate between four situations:

  1. The user has been marked as “Logged In”
  2. The user has been marked as “Logged Out”
  3. There is no user with the tag code that was sent
  4. The wrong API key was supplied

The ethernet shield allows your Arduino to operate as a Client or a Server. In this situation, I just want to use the client interface as I am connecting to a server to get information. Now let’s just look at the code required to make a simple HTTP GET request client with no parameters. I just modified this from the examples.

#include <Ethernet.h> // load ethernet SPI functions
 
// a MAC address that you make up to identify the Arduino
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// this is the IP that will identify the Arduino
byte ip[] = { 192, 168, 0, 160 };
// this is the IP of the server that we are trying to connect to
byte server[] = { 192, 168, 0, 101 }; 
 
//create the client
//wide area HTTP networks are on port 80 but my local rails app is on 3000
Client client(server, 3000);
 
void setup()
{
  //start ethernet
  Ethernet.begin(mac, ip);
  Serial.begin(9600);
 
  delay(1000);
 
  Serial.println("connecting...");
 
  if (client.connect()) { 
    Serial.println("connected");
    //this constructs the GET request, it is the equivalent
    //going to the browser and entering http://192.168.0.101:3000/main/index
    client.println("GET /main/rfid HTTP/1.1");
    client.println(); // print a newline char to tell the server we are done?
  } else { // this is called if conenction fails
    Serial.println("connection failed");
  }
}
 
void loop()
{
  if (client.available()) { // need to see if response has been read into the buffer yet
    char c = client.read(); //get next character and print it
    Serial.print(c);
  }
 
  if (!client.connected()) { //if we lose connection
    Serial.println();
    Serial.println("disconnecting.");
    client.stop(); // disconnects from the server
    for(;;)
      ;
  }
}

Some of this warrants a little more explanation for some…

Configuring the ethernet shield

First is the MAC address.

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

For those unfamiliar with basic networks, a MAC address is a unique number assigned to your network card that never changes. You don’t need to know much about it other than you need to make it up. You should be good if you use the one I have just used in this example but keep in mind that if you have multiple Arduinos connected to the same network, you may need to make up unique MAC addresses for each one.

Next is your IP.

byte ip[] = { 192, 168, 0, 160 };

This array refers to the IP that you want your Arduino to take. The Arduino Ethernet Shield currently ?doesn’t support DHCP?, so you have to choose an unused IP yourself. There are a variety of ways and steps to do this. First what you need to do is figure out what the first three bytes in this array need to be. This is determined by the local router you are connecting to. For instance, Linksys is usually 192.168.1.XXX and D-Link, in my case, is usually 192.168.0.XXX. You can find out what your situation is by checking the IP of a computer on that network. Then you need to choose an unused number for the last byte, usually between 100 and 255. If you are on a network with few computers, around 150 is usually a safe bet. If you are not sure or have a lot of computers on the network, you should find a way to log into your router’s admin interface and check the DHCP information. It will tell you all the IP addresses that are currently assigned and you can make one up an unused one based off that.

Last is the server’s IP.

byte server[] = { 192, 168, 0, 101 };

This is the IP of the server that you are trying to connect to. In my case, it is a laptop running my Rails application connected to the same network. If you want to connect to a server outside your network, on the internet, you need to find it’s IP. Your computer usually does this under the surface using DNS but you will have to do it manually here. One way you can do this is by pinging the domain name and seeing what IP it resolves to.

Sending information to a server

So, this example works out for many situations, but how can I send information to the server where my Rails app is being run? In my case, I need to send the API key and and the RFID tag I just read. What we need to do is build a query string. If you aren’t sure what that means, you will have to read that wikipedia article carefully. Let’s reexamine the code:

//I changed this line
client.println("GET /main/rfid HTTP/1.1");
//to this line
client.println("GET /main/rfid?apikey=123&tag=0123456789 HTTP/1.1");

When I run this code, I see this on the serial port:

connecting…
connected
HTTP/1.1 200 OK
Connection: close
Date: Mon, 26 Oct 2009 01:12:43 GMT
ETag: “8da44df37e592a5020e852d50fc31a64″
X-Runtime: 8
Cache-Control: private, max-age=0, must-revalidate
Content-Type: text/html; charset=utf-8
Content-Length: 8

^=NOUSER

This is the HTTP response. The last bit:

^=NOUSER

Is what I have defined in the Rails application to tell the Arduino what has happened. Just for clarification, this is what the rfid function looks like in the Rails app:

  #login via rfid service, has no view
  def rfid    
    if params[:apikey] == $api_key
      @user = User.find_by_rfid_tag(params[:tag])
      if @user
        @user.in_space = !@user.in_space
        @user.save
        if @user.in_space
          render :text => "^=IN"
        else
          render :text => "^=OUT"
        end
      else
        render :text => "^=NOUSER"
      end 
    else
      render :text => "^=KEYFAILED"
    end
  end

I tested a few different query strings and made sure it worked for all conditions and it did. Now I need a way to dynamically send the tag that we read from the reader. As you might have read in my RFID post, I am storing the RFID tag in a 10 character array:

#define CODE_LEN 10
 
char tag[CODE_LEN];

I initially thought I could do this:

client.print("GET /main/rfid?apikey=123&tag=");
client.print(tag);
client.println(" HTTP/1.1");
client.println();

Notice that I am using a series of print()s to build a string and ending it with println() to close it out with a newline. The only problem is that this doesn’t work. My Mongrel server (the Rails server) was telling me that my HTTP request were invalid. It seems like a lot of other people were running into this problem as well. After temporarily giving up, I realized the problem. I was reading an essay by Brian Kernighan, one of the creators of the C programming language, about a simple regular expression parser that he uses to teach students about programming methodologies. Scanning through the code, I was reminded that a character array cannot be interpreted as a string without a terminal null character ‘\0′ as the last element. So, I handled this situation like this:

#define CODE_LEN 10
 
char tag[CODE_LEN + 1];
tag[CODE_LEN] = '\0';

This didn’t affect any of my other code and now the tag array can be interpreted as a legit string :) I love simple solutions.

Now I need a way to parse the response. The reason my responses had this format ‘^=XXXXXXX’ was so I could do something like this:

/**
 * Finds result that we are looking for in the returned HTTP response
 */
char getHTTPResult() {
  while (client.read() != '^') {}
  if (client.read() == '=') {
    return client.read();
  } 
  return 'x';
}

This would return the first character for the response I am looking for. For example, with the NOUSER message, I would get back the ‘N’ character. I implemented this but the problem is that it was really slow. Or at least, it was a lot slower than it could be. The problem is the amount of pointless HTTP data you have to read before you get to the actual message, or it could be that I am printing all that data? Doesn’t matter because I can make it faster. I could have configured my server to not spit out so much junk, or I could just place the message earlier in the response.

Reverse REST

The first thing you return is the status code so why not put it there? As I said before, there are only four states I am trying to identify and there are plenty of HTTP status codes to represent them. So I modified the Rails controller to look like this:

 
  #login via rfid service, has no view
  def rfid    
    if params[:apikey] == $api_key
      @user = User.find_by_rfid_tag(params[:tag])
      if @user
        @user.in_space = !@user.in_space
        @user.save
        if @user.in_space
          render :status => 400 #IN
        else
          render :status => 401 #OUT
        end
      else
        render :status => 402 #NOUSER
      end 
    else
      render :status => 403 #FAILED
    end
  end

I can’t help but wanting to call this ‘reverse REST’, LOL. Rerunning my simple “no user” test, I now get this:

HTTP/1.1 402 Payment Required
Connection: close
Date: Sat, 06 Feb 2010 02:45:19 GMT
X-Runtime: 12
Content-Type: text/html; charset=utf-8
Cache-Control: no-cache
Content-Length: 0

This is much quicker to parse. I probably could have used some nice code to make this more flexible, but just hardcoding the digit read process in is probably easier and just as reliable, if not more efficient:

char getHTTPResult() {
  while (client.read() != '4') {} 
  if (client.read() == '0') { //just to make sure
    return client.read();  // return either '0' or '1' or '2' or '3'
  } 
  return 'x';  // something bad happened
}

At this point a simple switch allows us to define the behavior of the response:

void sendToServer() {
   client.flush(); //just to be sure
   if (client.connect()) {
      client.print("GET /main/rfid?apikey=123&tag=");
      client.print(tag);
      client.println(" HTTP/1.0");
      client.println();
 
      Serial.println();
      switch (getHTTPResult()) {
        case '0':
           Serial.println("logged in"); break;
        case '1':
           Serial.println("logged out"); break;   
        case '2':
           Serial.println("no user"); break; 
        case '3':
           Serial.println("API key failed"); break;    
        default:
          Serial.println("broke"); break;
      }
      client.flush(); //just to be sure, probably not needed here
      client.stop(); //should stop it
  } else {
    Serial.println("connection failed");
  }
}

A few more troubleshooting tips (will keep updated as they come in)

  1. Be sure to use flush() when appropriate. This ensures that your input buffer is clean and that you don’t have any left over remnants.
  2. I noticed that sometimes the ethernet shield would not power up when I plugged in my Arduino. You can tell by the group of lights on the top. I could only get it to start up when I had unplugged anything that was leaching power from my board (in my case the RFID reader which is leaching current off the 5V pin). I am not 100% sure why this is but my guess is that it has something to do with some components on the ethernet shield not getting enough current to start it up. If this happens to you, you will often find that client.connect() will return false every time. I will try to investigate this further.

Conclusion

Hopefully this isn’t too far out of context for your applications. Feel free to post questions about this device and I will try to help out.

Posted in Arduino, Tutorial/Documentation | Tagged , , , | 1 Comment

Agenda For Our First Official Board Meeting

Gumbo Labs, Inc. Board Meeting

4820 Banks Street, Studio #5, New Orleans, LA 70119

Jan 19, 2010, 7:30-9:00PM

Call Meeting to Order

Membership Business

  1. Review Applications
  2. Confirm Membership

Board Business

  1. Confer Incorporators as Officers
  2. Elect Board of Directors
  3. Discuss Board Waiver
  4. Adopt Bylaws
  5. Authorize Treasurer’s Duties
  6. Elect Officers
  7. Authorize Officers’ Duties
  8. Discuss Indemnification
  9. Discuss Officer Reimbursements
  10. Select Agent for the Corporation

Adjourn Meeting

Posted in Board of Directors | Leave a comment

Simon Dorfman’s Pecha Kucha Presentation about Gumbo Labs Video

Above video also viewable on vimeo. And the slides from this presentation were posted here.

I’ll try to update this post later with a summary and some links from the slides.

Posted in Uncategorized | 2 Comments

Tuesday Night Meeting 7:30 – 9:00

Is there anything in particular you’d like people to bring or prepare for this Tuesday’s meeting? Leave a comment. Otherwise it will be the usual hanging out, socializing, working on stuff together, what-have-you…

Posted in Uncategorized | 1 Comment

Slides from My Gumbo Labs Presentation at Pecha Kucha Last Night

Posted in Presentation | Leave a comment

Parallax RFID Reader <--> Arduino

A while back, I purchased a Parallax RFID reader and used it for authentication for my house door. It was kind of a hack job and wasn’t as stable as I would have liked so I never documented it and put it on the backburner. I recently decided to revisit the device for a project for Gumbo Labs.

The Parallax reader

The Parallax reader

BTW, you can now get this at your local Radioshack?!?. Maybe they are starting to move in the right direction again? Who knows.

Anyway, this device was initially easy to get running but it was not as stable as I hoped it would be. The example code online did not fully account for the quirks of this reader. I had to closely read the manual to make it work as expected. I am going to briefly describe how to get the best out of this reader and properly integrate it with your Arduino.

First you want to get them connected. The quickest way to do this is with a breadboard and some wires like this guy does:

Connecting Arduino to RFID reader

Connecting Arduino to RFID reader

The mapping should be similar to this:

  • Arduino serial RX to Parallax TX
  • Arduino GND to Parallax GND
  • Arduino digital pin (i.e. #2) to Parallax /ENABLE
  • Arduino +5V to Parallax Vcc

Keep in mind that when you upload your binary to the Arduino, you may need to disconnect the Parallax TX connection, just a warning.

Now to the Arduino code…

I will explain each piece in detail and give the whole code at the end. If you are impatient and hate learning, go there.

First let’s deal with this /ENABLE pin. Here is what the documentation says about it:

The RFID Card Reader is activated via the /ENABLE line. When the RFID Card Reader is powered and the /ENABLE line is pulled HIGH, the module will be inactive (standby mode) and the LED will be GREEN. When the /ENABLE line is pulled LOW, the RFID Card Reader enter its active state and enable the antenna to interrogate for tags. The current consumption of the module will increase dramatically when the module is active.

So, when the pin is HIGH, the reader is inactive and in a low current consumption mode. When the pin is LOW, the reader is active and can read tags. To utilize this pin, I created two functions:

#define RFID_ENABLE 2  //pin connected to ENABLE
 
void enableRFID() {
    digitalWrite(RFID_ENABLE, LOW);
}
 
void disableRFID() {
    digitalWrite(RFID_ENABLE, HIGH);
}

The usage of this functionality depends on your application. If you (and by you here I mean the Arduino) know when you will need to read a tag, keep the reader inactive until then to conserve current. This situation is not as likely as you usually want the Arduino to just know when a tag is next to it at any time. In this case, we will use it to briefly deactivate the reader after a tag is read. This will keep the Arduino from getting duplicate or junk/half reads and it will reset the reader for the next tag.

Reading a Tag’s Unique ID

As the documentation describes, when the reader is in active mode and a tag is placed near the antenna, a 12 byte message will come across the Parallax TX serial line. The documentation says this about the serial configuration:

All communication is 8 data bits, no parity, 1 stop bit, and least significant bit first (8N1). The baud rate is configured for 2400 bps, a standard communications speed supported by most any microprocessor or PC, and cannot be changed.

8N1 is the standard for your Arduino, you just have to tell it to start up the UART at 2400 baud in your setup() function:

Serial.begin(2400);

The designer of the RFID reader, KingPin if I am not mistaken, designed a custom protocol so we can determine where the tag starts and ends. Once again, we refer to the documentation (click to get a larger view of the picture):

RFID tag message protocol

RFID tag message protocol

The start byte and stop byte are used to easily identify that a correct string has been received from the
reader (they correspond to a line feed and carriage return characters, respectively). The middle ten bytes are the actual tag’s unique ID.

In other words, you should read the incoming serial bytes until you find the start byte [hex 0x0A || decimal 10 || line feed]. You should then read the next 10 bytes as the tag’s unique ID and hope that the stop byte [hex 0x0D || decimal 13 || carriage return] shows up last. BTW, if you ever need to know something like the hex and decimal values of line feed, check here.

Now let’s take a look at the piece of code which reads the tag. I am going to litter it with comments, it looks huge but it is actually pretty concise:

//you need to define these
#define CODE_LEN 10          //Max length of RFID code
#define START_BYTE 0x0A   //decimal 10 or LINE-FEED
#define STOP_BYTE 0x0D     //decimal 13 or CARRIAGE-RETURN
 
char tag[CODE_LEN];    //this is the character where we store the tag
 
/**
 * Blocking function, waits for and gets the RFID tag.
 */
void getRFIDTag() {
 
  /**
   * next_byte is temporary storage for every byte we read
   */
  byte next_byte;
 
  /**
   * this next part blocks the code until we get something in
   * the incoming serial buffer. This is what makes this a
   * "blocking function". You may want to comment this out
   * if you have stuff to do if a tag is not present.
   */
  while(Serial.available() <= 0) {}
 
  /**
   * if we get here, there is at least one byte in the buffer
   * the next if reads it and checks to see if it is the start_byte
   * if it isn't, we are just moving on.
   */
  if((next_byte = Serial.read()) == START_BYTE) {
    //bytes_read keeps track of how many bytes into the tag we are
    byte bytes_read = 0; 
 
   /**
    * This while loop makes sure we don't read
    * more bytes than we can store in tag array.
    */
    while(bytes_read < CODE_LEN) {
      if(Serial.available() > 0) { //wait for the next byte
 
          /**
           * Here we read the next byte and make sure it
           * is not the STOP byte, if it is, we must break
           */
          if((next_byte= Serial.read()) == STOP_BYTE) break;        
 
          /**
           * Now we store that byte into the
           * tag at the next position by incrementing
           * bytes_read and storing next_byte at that position
           * in the tag array.
           */
          tag[bytes_read++] = next_byte;
      }
    }
  }
}

Dealing with radio interference

Let’s say you implement the getRFIDTag() function like this:

void loop() {
  enableRFID();
  getRFIDTag();
  disableRFID();
  sendCode();
  delay(3000); //wait 3 seconds
  Serial.flush();
  clearCode();
} 
 
/**
 * Clears out the memory space for the tag to 0s.
 */
void clearCode() {
  for(int i=0; i<CODE_LEN; i++) {
    tag[i] = 0; 
  }
}
 
/**
 * Sends the tag to the computer.
 */
void sendCode() {
    Serial.print("TAG:");  
    for(int i=0; i<CODE_LEN; i++) {
      Serial.print(tag[i]); 
    } 
}

So, you have this running and you are using the Arduino’s serial listener in the IDE, and you notice that every once in a while, you get a random tag for no reason. This kind of bug can be a problem and it is one of the things that made my door authentication device so unstable. I wish I would have RTFM a little closer:

The Parallax RFID Card Reader, like many RF devices, may experience RF noise in its frequency range.
This may cause the reader to transmit a spurious tag response when no tag is near the unit. This will not
affect most uses of the RFID Card Reader. To completely prevent spurious responses, it is recommended
to simply read two responses in a row within a given amount of time (e.g. 1 second) to ensure that you
are reading a valid tag and not a “tag” generated by noise.

I originally thought I was the lone genius who came up with this solution until I read that paragraph :( Oh well.

Let’s look at a way we can implement this idea. I noticed when you hold a tag to the reader, considering you don’t deactivate after a read, it just continues to spit out the number until you pull the tag away. So, what we need is a function that is called immediately after getRFIDTag() that reads the code again and validates that it is the same. Most of this function is the same as getRFIDTag(), and I hate to break DRY principles, but we are going for simplicity here and I don’t want this to turn into tutorial on pointers!:

/**
 * Waits for the next incoming tag to see if it matches
 * the current tag.
 */
boolean isCodeValid() {
  byte next_byte;
  while(Serial.available() <= 0) {}
  if((next_byte = Serial.read()) == START_BYTE) {
    byte bytes_read = 0;
    while(bytes_read < CODE_LEN) {
      if(Serial.available() > 0) { //wait for the next byte
          if((next_byte = Serial.read()) == STOP_BYTE) break;
          /**
           * this is the only part that is really different,
           * if we find one byte that is off, we return false,
           */
          if(tag[bytes_read++] != next_byte) return false;
      }
    }
  }
  return true; // if we get here, 'it must be good'
}

So, this is all good right? No, not really. If you were able to see a problem with this line:

  while(Serial.available() <= 0) {}

you are very perceptive. This will work for real tags but will make things complicated when noise occurs. Consider the believable case in which we get a junk tag from noise every 30 minutes. When we get that junk tag, we will be stuck on that line. One way to get around it is to apply a timeout. Here is a pretty ghetto way to implement that, just change the above line to this [UPDATE, there is a bug with this, see end of page]:

  int count = 0;
  while(Serial.available() <= 0) { //passes when we get a byte
    delay(1); //wait one millisecond
    if(count++ > VALIDATE_LENGTH) return false; //else check again
  }

We define VALIDATE_LENGTH to be the number of milliseconds, roughly, that the isCodeValid() function will wait until it realizes the tag you are asking to validate is just noise.

#define VALIDATE_LENGTH 200 //wait 200 ms

So, now you should be good to go. If you are looking to storing and comparing keys in non-volatile memory, I suggest looking at the EEPROM library. I already wrote some code to do this so if you are curious let me know in the comments. As promised, here is all the code for this article:

/**
 * author Benjamin Eckel
 * date 10-17-2009
 *
 */
#define RFID_ENABLE 2   //to RFID ENABLE
#define CODE_LEN 10      //Max length of RFID tag
#define VALIDATE_TAG 1  //should we validate tag?
#define VALIDATE_LENGTH  200 //maximum reads b/w tag read and validate
#define ITERATION_LENGTH 2000 //time, in ms, given to the user to move hand away
#define START_BYTE 0x0A 
#define STOP_BYTE 0x0D
 
char tag[CODE_LEN];  
 
void setup() { 
  Serial.begin(2400);  
  pinMode(RFID_ENABLE,OUTPUT);   
}
 
void loop() { 
  enableRFID(); 
  getRFIDTag();
  if(isCodeValid()) {
    disableRFID();
    sendCode();
    delay(ITERATION_LENGTH);
  } else {
    disableRFID();
    Serial.println("Got some noise");  
  }
  Serial.flush();
  clearCode();
} 
 
/**
 * Clears out the memory space for the tag to 0s.
 */
void clearCode() {
  for(int i=0; i<CODE_LEN; i++) {
    tag[i] = 0; 
  }
}
 
/**
 * Sends the tag to the computer.
 */
void sendCode() {
    Serial.print("TAG:");  
    //Serial.println(tag);
    for(int i=0; i<CODE_LEN; i++) {
      Serial.print(tag[i]); 
    } 
}
 
/**************************************************************/
/********************   RFID Functions  ***********************/
/**************************************************************/
 
void enableRFID() {
   digitalWrite(RFID_ENABLE, LOW);    
}
 
void disableRFID() {
   digitalWrite(RFID_ENABLE, HIGH);  
}
 
/**
 * Blocking function, waits for and gets the RFID tag.
 */
void getRFIDTag() {
  byte next_byte; 
  while(Serial.available() <= 0) {}
  if((next_byte = Serial.read()) == START_BYTE) {      
    byte bytesread = 0; 
    while(bytesread < CODE_LEN) {
      if(Serial.available() > 0) { //wait for the next byte
          if((next_byte = Serial.read()) == STOP_BYTE) break;       
          tag[bytesread++] = next_byte;                   
      }
    }                
  }    
}
 
/**
 * Waits for the next incoming tag to see if it matches
 * the current tag.
 */
boolean isCodeValid() {
  byte next_byte; 
  int count = 0;
  while (Serial.available() < 2) {  //there is already a STOP_BYTE in buffer
    delay(1); //probably not a very pure millisecond
    if(count++ > VALIDATE_LENGTH) return false;
  }
  Serial.read(); //throw away extra STOP_BYTE
  if ((next_byte = Serial.read()) == START_BYTE) {  
    byte bytes_read = 0; 
    while (bytes_read < CODE_LEN) {
      if (Serial.available() > 0) { //wait for the next byte      
          if ((next_byte = Serial.read()) == STOP_BYTE) break;
          if (tag[bytes_read++] != next_byte) return false;                     
      }
    }                
  }
  return true;   
}

I have tested this as well as I can. I have yet to catch any noise events ‘in the wild’ so to speak, which concerns me [read Updates, lol]. But I have tested each case in the isCodeValid() function. I have caused a false validation by timeout and by differing keys [repetitive noise]. But I have also broken it by causing it to read “half” of a key. If it still doesn’t work for you, get creative, there are many ways around the interference issue.

Please let me know if you find faults or improvements and Enjoy :)

Updates

02/07/2010 – For those of you who have been using this code and still getting some noise, I apologize because I just found a bug with the isCodeValid function. For some reason, I was not getting past the line:

if ((next_byte = Serial.read()) == START_BYTE) {

I ran this code right before that line:

  for (int i = 0; i < 30; i++) {
    Serial.print("a");
    Serial.print(Serial.available(), DEC);
    Serial.print("r");
    Serial.print(Serial.read(), DEC);
    Serial.println();
  }

And this came on the port:

a1r13
a0r-1
a0r-1
a0r-1
a0r-1
a0r-1
a0r-1
a0r10
a6r48
a10r52
a9r49
a8r54
a9r50
a15r66
a17r69
a16r65
a15r49
a14r54
a13r13
a12r10
a11r48
a10r52
a9r49
a8r54
a7r50
a6r66
a5r69
a4r65
a3r49
a2r54

Now, ignore the line a0r10. It is not a bug, it is just that it takes so long to print to the serial port at 2400 baud. Anyway, what is obvious is that my whole function was breaking b/c the STOP_BYTE (13), was still in the buffer. I tried to do a flush before the function but that didn’t work for whatever reason. So what I did is change the while loop to this:

while (Serial.available() < 2) {

and then after the while loop breaks, throw that 13 away:

Serial.read();

Sorry this took so long for me to figure out, I was on hiatus, I hope it didn’t mess anyone up. This change is reflected in the whole piece of code.

Posted in Arduino, Tutorial/Documentation | Tagged , , , | 17 Comments

Hacking the Asus WL-520GU w/ OpenWRT

I was at a Gumbo Labs meeting recently and one of the members, Mark, showed us the router that he had been working on. He had flashed it with OpenWRT, added an SD card, and a serial GPS module. He used it to collect geospatial network information on the way to the meeting for the demonstration. What interested me the most was the expansive abilities of OpenWRT, as well as the relative cheapness of some of the routers that could host it. According to Mark’s logic, why buy an Arduino when you can spend a little more and have linux, wireless, and a higher level programming language? I still think the Arduino has it’s place in my life, mostly considering you can go from the Arduino to a real, sell-able, AVR prototype easily and for extremely cheap. For certain situations though, using a hacked router is a great idea. So I decided to do some research and I came across the Asus WL-520GU.

the 520gu

the 520gu

You can pretty much ignore the specs you see online because they aren’t really important. Here are the real specs to this device:

  1. It is extremely small, can run off 5 Volts, and doesn’t consume much current. You can easily run it on a battery.
  2. You can easily find builds of OpenWRT for the Broadcom chip found in the Asus. Flashing it is simple. OpenWRT is among the more hackable and useful of the WRT firmwares. You can SSH, telnet, or log in over serial.
  3. Asus left a 3.3V serial port right on the board, just solder in a 4 pin header and you got serial communications. You can log into the board from there or you can have your programs access it and send the info out to the world.
  4. There is a USB port. You can use some cross-compiled linux packages to access that serial port. This opens up a lot of room for creativity. The most important thing about it is that it gives you more space to store cool stuff, like a python interpreter!
  5. That leads us to the thing I was most excited about, you can run python scripts on the router. And you can use pySerial to access the serial port!

So, how do we go about hacking this? Well, there are a few initial steps. I figured all of this out by reading these two articles

but I am going to go through all the steps here so I can clarify some things. You should read those and then reference them when I am not making sense. I copied a lot verbatim.

First off, we must take apart the router.

Taking off the casing

Taking off the casing

BTW, sorry for the crummy pics, I had to use my phone. Anyway, to take this thing off, unscrew the two visible screws then flip out the corner of the rubber feet on the top-left and bottom-right. There are two hidden screws there. After we remove the casing, you can pull out the board.

After the case is removed

After the case is removed

Now we need to locate the convenient 3.3V serial port that the Asus designers left on the board. It is pretty easy to spot. It is this empty space for a 4 pin jumper. The pin-outs from top to bottom in this picture are 3.3V – RX – TX – GND.

3.3V serial port left by asus designers

3.3V serial port left by asus designers

Now you need to desolder this port so you can get access to it. I found this more difficult than it usually is. To keep you from going through the same, I recommend the following steps:

  1. Desolder from the bottom of the board. There are some delicate traces on the top and you don’t want to cause a short.
  2. You may need to use a little solder to get the old solder to flow.
  3. Don’t heat the board too long, you could damage nearby components or traces.
  4. Use some good wick, not a sucker. This is one of the few times I will recommend you head over to Radio Shack. Their solder wick is great! Unfortunately, I used this bulk Chinese crap.
Cheap ass thin wick

Cheap ass thin wick

Here is what happens when you use bad wick:

Desoldered port

Desoldered port

Not the worst desoldering ever done, I have heard of people bricking routers this way, but certainly not as clean and easy as it should have been.

Next we need to connect this to our computer. Since this is just basically a serial port, you can use a variety of old hardware. Just remember, this doesn’t follow the standard RS-232 specification of 12 Volts! It is only 3.3. Most people have used the FTDI TTL serial to usb cable for this. I happened to have a few extra FTDI chips lying around for such hacking occasions.

FTDI 232 chip on breakout board from Sparkfun

FTDI 232 chip on breakout board from Sparkfun

I couldn’t find any female headers in the lab so I just grabbed a breadboard and some wires. I soldered the wires directly into the board. You normally want to solder on headers but I didn’t have a need for this at the time b/c once you get OpenWRT on this thing, you can SSH in. The mapping is simple. Cross RX and TX, makes sense if you think about it, and connect grounds to each other. No need to connect the 3.3V on either side.

Serial conection

Serial conection

Once I plugged it in, I checked to see if the FTDI drivers were working and the port was recognized. You also need to know the unique name of the device. I opened up the terminal and checked my /dev folder for descriptors starting with tty.usb.

searching for serial interface

searching for serial interface

Now that I know the port is working and where it is, I wanted to see if I could listen in on the Asus firmware as it starts up. I opened up ZTerm, set it to /dev/tty/usbserial-A3000RBH, set the baud rate to 1152oo, and set the protocol to the standard ASCII 8N1 (8 bits, No parity, 1 stop bit). Then I did a hard restart on the router [turning my surge protector off then on], and saw the boot log stream into my ZTerm window.

ZTerm showing boot of Asus firmware

ZTerm showing boot of Asus firmware

Now we need to install openWRT. You can build it yourself, but I recommend getting this pre-built version from mightyOhm. Next you need tftp. I know OS X has it, not sure about other OSs. After you have all this gathered, you need to configure your LAN network interface to use a static ip and connect directly to your router. We are going to tftp the openWRT firmware over to the router. The process for this is different for all OSs, but you basically need these settings

  • ip: 192.168.1.XXX #just make up something for XXX that isn’t used, like 180
  • subnet mask: 255.255.255.0
  • router: 192.168.1.1 #this is the default ip of the router

After you are set up, connect up an ethernet cable from your computer to LAN port 1 on your router.

plugged into LAN 1

plugged into LAN 1

Unplug your router, hold down the black restore button, and plug back in. After a few seconds, you will see the router trying to read a tftp connection in your ZTerm window. It will be saying

Failed.: Timeout occurred

Reading:: TFTP Server.

Over and over again. What you need to do is connect to the router over tftp and upload the openwrt firmware you downloaded earlier.

I opened up a terminal and ran these commands. Your process may slightly differ

$ cd ~/Downloads/ #this is where my trx file was
$ tftp
$ trace
$ timeout 1
$ mode binary
$ connect 192.168.1.1
$ put openwrt-brcm-2.4-squashfs.trx

Once you run the last command, you should see the router accept and start to upload. Don’t touch anything at this point!

Flashing the router over tftp

Flashing the router over tftp

Wait for it to say done. XXXX bytes written as seen above. It may take a few minutes, be patient. After this, you can restart the router and watch ZTerm and if all goes well, hit enter when asked and you should see openWRT start up!

openWRT boot

openWRT boot

OpenWRT comes with busybox so you have most of the normal linux commands like ls:

LS

LS

Now, we want to set up our network interface. I wanted to turn the wireless router into a wireless client. All we have as a text editor is vi so you may need to brush up on it’s use.

First we must set up the wireless interface:

root@OpenWrt:~# vi /etc/config/wireless

edit it to look like this with your own settings:

config wifi-device  wl0
	option type     broadcom
	option channel  2  # the channel your wireless network is on

	# REMOVE THIS LINE TO ENABLE WIFI:
	# option disabled 1 (comment out or remove this line entirely)

config wifi-iface
	option device   wl0
	option network	lan
	option mode     sta  # configures the router to connect to your network
	option ssid     MyNetwork # the SSID of your network
	option encryption wep  # the encryption mode of your network
	option key	XXXXXXXXXX  # add this line with your WEP key

Then set up DHCP:

root@OpenWrt:~# vi /etc/config/network

Edit it to look like this commenting out last 2 lines:

#### LAN configuration
config interface lan
      option type     bridge
      option ifname   "eth0.0"
      option proto    dhcp
      #option ipaddr   192.168.1.1
      #option netmask  255.255.255.0

Check your resolve.conf file:

root@OpenWrt:~# cat /etc/resolv.conf

It should say this, if not, make it so:

nameserver 127.0.0.1

Now we can restart the network interface:

root@OpenWrt:/# /etc/init.d/network restart

And we should be able to ping something!

pinging google!

pinging google!

After this, we now have a functioning linux machine! Not bad for 25 bucks. Now I desoldered the serial port hack job [unplug first], and I can SSH or telnet into the router:

SSHing into the asus

SSHing into the asus

If I remember correctly, the username and password were both root.

I have had a few ideas about what to do with this. I think the one I am going with is a home power monitoring system similar to this one :

http://www.picobay.com/projects/2009/01/real-time-web-based-power-charting.html

The basic architecture would be AC clamps in my breaker box -> arduino -> serial port on asus -> python script running off usb -> pachube over wireless connection. I originally thought python would be perfect for this, and it probably is, but I ran into some issues getting USB to work. It was a pain in the ass. Then I realized, do I actually need to write a program to get the info from the serial port to the web? Hello no! I got linux to work with, and linux people have been doing this since the beginning of networks. Fortunately, I found this page that had exactly what I was looking for. Here is the bash script he uses:

#!/bin/sh
while [ 1 ]
do
temp=$(grep -m 1 “temp” /dev/ttyS0|cut -d “=” -f 2)
curl –request PUT –header “X-PachubeApiKey: your-key-here” –data “$temp” “http://www.pachube.com/api/1931.csv”
sleep 300
done

He is basically just listening in on the serial port and parsing the incoming string then piping it to curl [which can be obtained on the Asus via the package manager opkg]. He is using it for temperature but it can easily be adapted for my purposes.

I am waiting to get an AC clamp in and when I do, I will write a part 2 with the rest of the project.

Posted in Tutorial/Documentation | Tagged , | 4 Comments

Install GnuCash On Mac OS X

Install

My quick list of commands for getting GnuCash (plus documentation) installed on Mac OS X 10.5.8 (you’ll need to have MacPorts installed for this):

sudo port install gnucash
sudo port install gnucash-docs
sudo port deactivate mesa
sudo port -v upgrade outdated
sudo port deactivate mesa

You can read all the details about why mesa needs to be deactivated in this thread.

Launch App

I decided to get all fancy and create an applescript launcher for GnuCash so that I could launch GnuCash with one click.

If you want to do it the old fashioned way, here’s how:

Open X11 and type:

gnucash

…into the xterm command line to launch GnuCash.

Read the Documentation

GnuCash Docs don’t seem to work out of the box, so I suggest bookmarking this local documentation to read in the browser.

file:///opt/local/share/doc/gnucash/index.html

I also amended the applescript launcher to also open the documentation.

Fancy Graphic

I gave the applescript launchers a fancy graphic so you could easily recognize them if you wanted to keep it in your dock. Feel free to download the zip of PSD files and make changes or do whatever you want with it.

PSDs and ICNS in ZIP

PSDs and ICNS in ZIP

Posted in Tutorial/Documentation | 3 Comments