Lego mount for Arduino

Arduino — Dillon @ 6:13 pm

I got to thinking (that’s another story) about the old Technics set that I had when I was a kid and how useful it would be if I could tear down and build things without having to hacksaw stuff (i.e. like with the Microrax stuff). We had major flooding recently (after an earthquake and a hurricane) and the closed roads funneled me to a toy store. Was this a sign? I’m not sure. All I know is I have a Mindstorms kit now. :)

So I built an Arduino frame using nothing but the parts from the Mindstorms kit (it’s all just Technics parts). It’s pretty sturdy and the little rubber ends hold the board down pretty good. I figure it’s good enough to put on wheels or a quad-ped bot. I don’t know if I’d send it up in the air. I’d probably want to add a few more cross bars in there. Anyway, I did a lot of refactoring (if you could call it that) and I think this design is pretty good. Here’s the money shot with the rest of the build shots so you can copy it. I’m fresh brand-new to the Lego scene so leave some comments if I did something stupid.

(more…)

Arduino Cat Faucet with Mongodb and Rails

Arduino,Noteworthy,Rails,Ruby — Dillon @ 11:01 pm

I built a robot arm for my cat during a month-long geekcation. :) Here are some shots of the web interface. The graph shows the percentage of the day that she drinks.

Final hardware rig

Background

My cat likes to drink fresh and cold water directly from the faucet. We get up and turn on the faucet only to leave it running after she’s jumped down. It’s not really a big problem for us but I saw a fun problem that I could work on. As much as this seems like a weird and freakish oddity, it’s a potential start of a smarthome sensor network that may provide some utility. I also saw an opportunity to learn various things such as MongoDB, mechanical construction with Microrax, Rails3 and more development on Arduino with an Xbee module.

(more…)

Arduino command protocol

Arduino,C/C++ — Dillon @ 11:40 am

UPDATE: Use CmdMessenger instead of Messenger.

Here’s my IRC Arduino Bot. It uses a regular Arduino 328 and an Ethernet Shield both from sparkfun. As for software, I’m using the Ethernet2 library (see my previous post about this), the WString library and a homerolled IRC protocol parser. The breadboard’s power is connected to arbitrary pin 5 and some resistors to keep the LED from burning out.

arduino_irc_light

Basically, my bot joins an IRC channel and then listens for PRIVMSG commands starting with a password. It takes those commands and controls an LED. For example, I’d send this privately to the Arduino:
command password LEDON

And then the red LED comes on. I tell it “LEDOFF” and it turns off. Ok, it’s not a new RFC spec worthy of IEEE recognition and international adoption. But it got the job done in a human-readable manner. Previously on my facebook status light project, I had done much of the processing on my laptop and only send hex codes to the Arduino to light up LEDs. The difference now is that the Arduino is doing the processing and no computer is needed.

While I was working on this little project, I had the bot join the channel and announce itself.
irc_log

At one point, I was working on code and then my bot would disconnect. I checked the serial monitor and the server seemed to drop me after a few minutes. The channel would say that I timed out. I realized that I wasn’t responding to the PING from the server. So I threw in some code that checks for anything from the server that starts with “PING :”. I then respond with “PONG”. I remember seeing PING?/PONG! messages in mIRC back in the day. Now it makes sense why mIRC was doing that in the console window.

It works great and I was excited about how much this little board could do in 14KB. And then I kept testing it. After about 7 or 8 “turn on” and “turn off” commands, the Arduino wouldn’t do anything anymore. It’s like it just froze. If I typed 5 commands, it’d stay connected for a long time. But every time I’d send it 7 to 8 commands, it would lock up. And by lock up, I mean the commands wouldn’t work anymore and it would time out from the server. WTF. So close!

So I figure that it’s something to do with pointers and memory. I really don’t have a solid grasp on pointers and C. I got a lot of this working by iterative experimentation over many days. So I was looking for a better way to send human readable commands to my bot. By human readable I mean something that works like a unix command “command arg1 arg2″. Of course this human readable bit introduces strings which is tricky enough in C (for me) and even worse on the Arduino. I figured this was a problem that someone smarter than me had solved.

I found a library called Messenger. It’s pretty simple to install, just throw it in your ~/Documents/Arduino/libraries folder on Mac and um … the equivalent on Windows? There are examples in the Messenger folder that you can checkout. HOWEVER the whole point of me posting this big long thing is the following.

The example checkString really threw me for a loop. It did exactly what I need it do to in a much cleaner way. I uploaded to the Arduino and then broke out to a shell.

$ screen /dev/tty.usbserial-A9005bCr 115200

Substitute your virtual usb device for the /dev/tty path. Note that the sketch uses 115k serial speed. You won’t see anything when you type but if you hit “enter” (to clear the buffer) “on[enter]” in screen LED 13 will turn on. Type “off[enter]” ([enter] means the enter key) and it will turn off. Great! Exactly what I need. But then I tried typing “on” then “off” then “muffins” then “on” and the light stayed off. Any garbage gets the Arduino stuck like my sketch. Ok, is what I’m trying to do impossible or is this just coincidence?

I modified the checkString example to look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// This example demonstrates Messenger's checkString method
// It turns on the LED attached to pin 13 if it receives "on"
// It turns it off if it receives "off"
 
 
#include <messenger .h>
 
 
// Instantiate Messenger object with the message function and the default separator 
// (the space character)
Messenger message = Messenger(); 
 
 
// Define messenger function
void messageCompleted() {
  // This loop will echo each element of the message separately
  while ( message.available() ) {
    if ( message.checkString("on") ) {
      digitalWrite(13,HIGH);
    } else if ( message.checkString("off") ) {
      digitalWrite(13,LOW);
    } else {       // ADD THIS
      break;     // ADD THIS
    }                // ADD THIS
  }
 
 
}
 
void setup() {
  // Initiate Serial Communication
  Serial.begin(115200); 
  message.attach(messageCompleted);
 
  pinMode(13,OUTPUT);
 
}
 
void loop() {
 
  // The following line is the most effective way of 
  // feeding the serial data to Messenger
  while ( Serial.available() ) message.process( Serial.read() );
 
 
}
</messenger>

I added the break and it’s able to deal with garbage. I tested more than 20 commands with banging on the keyboard in between and it seems pretty solid. Now I just need to integrate this with my IRC bot and I might have something that can stay online for a while.

By the way, after you use screen to connect to a serial port, hit “Ctrl+A, k” to kill the window and break out of screen.

Update: People have asked for the code. It’s posted after the break.
(more…)

Basic 555 timer Arduino project

Arduino — Dillon @ 4:27 pm

I put together the arduino protoshield from sparkfun. Excellent instructions at atomicsalad. Even though it’s a standard through-hole kit, atomicsalad’s instructions were nice to follow along.

After it was put together I had a few built-in LED lights to play with. I had seen this 555 timer in a piece kit I bought and I wondered what it does. I found a ton of examples and apparently you can do a zillion things with it. I wanted to start with the basics so I set out to make a light blink using only hardware. I’m only using the arduino for power in this one.

jump_breadboard_at_30
I found a great tutorial on youtube and modified it to work on a larger breadboard. I had some trouble because it turns out that this breadboard has its power rails split down the middle. I was confused and stuck on this for a day. Eventually I found a video that hinted at this fact and connected the two sides like so. After that, the power rails on each side will work like I expected. This is by design on these boards so that you can have two different voltages but I found it annoying.

So here’s the schematic that I followed for the configuration on the big breadboard.
555_bb

I transferred this layout onto a mini breadboard and it works like a champ. The protoshield has room for a mini self-adhesive breadboard. Here’s the actual wiring shot. This uses a light on the protoshield vs the light on the breadboard schematic. The concept is the same though. Pin3 on the 555 is the output which makes the light blink rapidly. You could use this chip as a cpu clock for example.
555_timer_wiring

You don’t have to use the breadboard switch (the black thing on the left), it’s just more convenient to flip a switch rather than plug in/out of the 3v. Oh yeah it’s powered by 3v on the arduino. The cap is 100uf. You can use 2x orange,orange,maroon (gold) resistors or one of those and a blue,gray,maroon one (sorry I don’t have the resistance values). Play with the resistor values to change the blink rate.

Ethernet2 Arduino Library Fix on 0017

Arduino — Dillon @ 10:58 pm

arduino_0017
Ethernet2 lib. It’s a lighterweight and better Ethernet class. Head into your ~/Documents/Arduino/libraries (or Windows equivalent) and checkout the SVN project:

$ svn co http://tinkerit.googlecode.com/svn/trunk/Ethernet2%20library/Ethernet2

Now change your sketch to use Ethernet2.h instead of Ethernet.h. Wondeful? No. You’ll get this error in 0017.

'EthernetClass' has not been declared

Ok, the forums have a fix. But it didn’t work for the longest time because I didn’t know what they meant by Server.cpp. There’s two of them! The original or the new one?! If you edit the old one you’ll get this:

Print.cpp:129: first defined here

So:
1. Edit Server.cpp in Ethernet2 to include Ethernet2.h and not Ethernet.h.
2. Delete the Print.cpp and Print.h files from Ethernet2.
3. Compile.
4. Have some yay.

Arduino Sessions

Arduino — Dillon @ 12:14 pm

seven_segment_ledHacking around with sparkfun shipments and components. I got a starter set with a box. Included a 7 segment led. Got it to display the number 4. Moved on to a capcitor test. Arduino playground has a read/discharge example. It reads how many milliseconds it takes to charge/discharge. I got it working but don’t understand it still. I did a potentiometer test. A basic rocker switch test. Resistors in serial, resistors in parallel. I made a push switch toggle on/off led light with a transistor (I think). Transistor testing (those things are weird). Just kinda went through the box and saw what did what. I want to understand multiplexing and make a 2 digit or more 7-segment LED display work. I have a bunch of wire and things to make it work now. I need a resistor kit, sparkfun was sold out recently but now they have them. It’s a kit of every resistor you can think of.

wingshield
I also put together a wingshield kit. I makes connecting wires to the arduino a little more stable because you can screw them into the screw terminals. I seriously screwed up at one point, snipping off the header pins when you aren’t supposed to snip them, doh (what will plug in to the headers if you snip the pins?). I had to desolder and use parts from another kit. Amazingly the desoldering went better (although it takes a long time) and the shield seems to work.

Sparkfun Onslaught

Arduino — Dillon @ 10:42 pm

simon_sparkfun
Sparkfun had their free day today. I tried to nab some stuff but their servers were too busy and I couldn’t sit there and refresh all day (what am I idle rich?). I just happened to have an order placed the week before and it all came in today.

WRL-08664 XBee 1mW Chip Antenna
DEV-09063 Arduino XBee Shield Empty
KIT-09285 Beginner Parts Kit
DEV-09282 ScrewShield
DEV-00666 Arduino USB Board
LCD-00258 Serial Enabled LCD Backpack
TOL-09465 Tool Kit - Beginner
TOL-09317 Third Hand
KIT-09343 Simon Game - Through-Hole Soldering Kit
TOL-00298 Wall Adapter Power Supply - 9VDC 650mA
SEN-08958 Infrared Proximity Sensor Long Range - Sharp GP2Y0A02YK0F
SEN-08733 Infrared Sensor Jumper Wire - 3-Pin JST

Chief amongst the loot was a soldering iron and a simon game kit. Really, I could care less if the thing worked. I wanted to learn soldering. I seriously have never done it before. I couldn’t believe my eyes when the damn thing lit up and worked! I thought for sure my scorch marks had screwed something up. When I was soldering the legs on the mega-168 processor the thing got warm. I was working kind of fast and nervous. I guess I didn’t burn anything too bad. Many of my connections look like shiz and I have pointy parts all over the place. I was really trying to peer and study how the solder was making the connections. I’d shake and bend the pins to see how much strength it had and so on. I was really surprised at out unintuitive the whole process is. You’d think it’d be harder but after doing the same pins over and over you start to see what a good solder bead looks like. I just followed the instructions (some of which were a bit off because of a newer board rev) and it wasn’t too hard when I took my time and read ahead making sure I wasn’t doing something stupid.

helping_handsCrazy pants! I can’t believe it worked! The cheapy soldering iron and solder they sent with a starter kit worked really well. I just held the solder inside the plastic tube it came in. I thought that the cheapy iron would be crappy but it worked well. I got some helping hands to help. They helped. :D What was also helpful was having a workbench, damp sponge, helping hands and some youtube videos for instruction. It’s just not as hard as I thought it was. Now SMD soldering, I have no idea how people do that.

So really I was expecting the kit to be a learning experience and I’d throw it away. But somehow, despite the weird and PCB-stress-inducing battery clips, the Simon game worked. When it lit up and I played a little game of simon, I was really surprised. Kristin has it on the coffee table and she plays it a lot. I don’t think she ever played it in the 80s, weird. I tweeted about my success and the freaking official Sparkfun twitter account saw my #sparkfun tag and congratulated me. Awesome!

After a holiday break, a sudden rush of software-type-hacky-motivation came to me. I grabbed my arduino and laptop and checked it out. First, it didn’t work. The laptop is new and I had to set up the dev-env again. Apparently the default now is the ATmega328 and my Arduino is based on the ATmega168. After that was settled, I had a led blinking again.

So I had this Hitachi based LCD panel that I had never done anything with. I got it powered (3.3v) and was trying to figure out how to run the thing. I read and read and found that I didn’t have the right crap on hand. First, it seems like there’s two ways to drive it. You can drive it “manually” with a bunch of parallel type wires or you can buy a serial backpack and solder it on (I think). I tried getting things working parallel but it turned out to be a little more than I was comfortable with. I don’t understand multiplexing yet and I actually didn’t have enough hook up wires to get it done. So part of the order you see up top is a serial backpack. Well somehow I managed to get it wired up but it’d short out my Arduino board, I was just using the board for power. My LED would fade away, it seems to do that when I short something out. Thinking that this was a power problem, I plugged in the 9v adapter with the usb (5v). Well then I started smelling a plastic smell. I heard a crackle and then I saw a little bubble appear on the backpack chip. Ow. I threw it away and I don’t have a picture of it. All it reminded me off is when Tim and I burned up a southbridge on my old AMD computer. Smells like fail.

So I just played around with the broken backpack. I desoldered some of the headers off for practice. Desoldering is hard, I burned up the PCB pretty bad but it was a good learning experience. Then threw it away. I ordered a proper serial LCD from sparkfun. I recently got that working electrically although the code side of it I need to clean up a little bit and grok it some more.

Facebook Arduino Lamp

Arduino — Dillon @ 7:42 pm

Overview

Facebook Chat
I built an arduino project that monitor’s Facebook online status (the chat app in the lower right when you are on the facebook page). It lights up bright when someone is Online, dimly lit when idle and is unlit when someone is offline. I wired 3 LEDs so it can only monitor 3 people as of right now. It won’t tell you who is who because there’s no text display. I suppose you could make little stickers. In the end, it’s a simple little project that provides a benefit of being able to have a small secondary display of who’s on and not. Is the little device a keeper? Would people want it? Probably not. This was a test.

It was a fun little project but it had a lot of challenges. First, this is an online app with dependancies on online resources. I read forums and wikis and saw that much has changed lately with Facebook’s API. So this is an article about how I got it working but doesn’t mean that it’s going to work for you. Things change online and at best this might be a starting point in how to “get your arduino online”. When things change online, this article can get dated.

And about that online bit. The arduino is just a simple microprocessor. I found that a lot of fancy Java features won’t run on it. Strings, System.arraycopy and many network Java packages just aren’t supported. So you’re going to need a laptop or computer hooked up to the arduino to make this work. The arduino doesn’t have a direct network adapter on it, a network stack or a lot of RAM. It’s job is to do the simple stuff like blink LEDs. So I found it’s best to keep the arduino code simple.

Two apps run. One is the Processing app which connects to Facebook and queries 3 facebook IDs for their status. One is an Arduino app that simply loads the code onto the Arduino. The Processing app has to stay open because it queries every 10 seconds and sends special codes to the Arduino. The codes may look like this:

#0FF = 1st LED full brightness, 1st friend is online
#110 = 2nd LED dimly lit, 2nd friend is idle
#000 = 1st LED off, 1st friend went offline
#2FF = 3rd LED full brightness, 3rd friend came online

The first character, #, is just a marker. The next character tells the arduino which LED to light up (starts with 0), The next two characters is a hexadecimal number telling how bright to light up the light 0-255. So the Processing app queries Facebook and sends a code over serial to the Arduino. The Arduino parses the code and changes the LEDs.

Dependencies

There are a ton of dependencies that you’re going to need.
- Facebook account
- A dummy app on facebook, instructions below.
- An infinite session key (also called offline access). This allows you to create a desktop app that doesn’t have to be in a web container (nor prompt for a facebook login).
- An arduino and some simple electronics components. I ordered a starter kit from Amazon for $40.
- Processing
- The arduino IDE
- A facebook java API from google code. It has some dependancies that should be covered by the below steps.

Wiring the arduino

facebook arduino lamp wiring
If you mess with the arduino a lot, it shouldn’t be a problem to wire 3 LEDs. But I’ll try my best with my non EE background and crappy drawing skills. The longer lead on the LED is the + side (the signal) and the shorter is the ground. Put your LEDs anywhere on your breadboard, + on the left. Run 3 signal wires to your breadboard and connect them to the + side (the left). Each LED needs to be grounded. I used a common ground along the top (the – symbol at the top left of the above diagram). I didn’t use the common + on the breadboard because each LED needs to light up independently.

facebook arduino lamp wiring photo
This is the basic approach I took wiring mine. Now, my green LEDs are weak so I added a few to make it brighter. My blue LED is blinding so I added a resistor in the lead to it (still is too bright). It’s pretty messy in there.

Arduino code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
int val = 0;
char buffer[7];
char oldBuffer[7];
int pointer = 0;
byte inByte = 0;
 
// define pins
int red = 10;
int green = 11;
int blue = 9;
 
byte r = 0;
byte g = 0;
byte b = 0;
 
void setup() {  
  // set pinouts
  pinMode(red,OUTPUT);
  pinMode(green,OUTPUT);
  pinMode(blue,OUTPUT);
 
  // open serial port
  Serial.begin(9600);
 
  Serial.println("DONE WITH SETUP!");
}
 
void loop() {
  if (Serial.available() > 0) {
    // read incoming byte
    inByte = Serial.read();
 
    if (inByte =='#') {
      Serial.println("Got something with #");
      Serial.println(inByte, DEC);
      while (pointer < 3) {
        buffer[pointer] = Serial.read();
        pointer++;
        Serial.println(buffer[pointer], DEC);
      }
     if (buffer[0] == '0') {     
      r = hex2dec(buffer[2]) + hex2dec(buffer[1]) * 16;
     }
     if (buffer[0] == '1') {     
      g = hex2dec(buffer[2]) + hex2dec(buffer[1]) * 16;
     }
     if (buffer[0] == '2') {     
      b = hex2dec(buffer[2]) + hex2dec(buffer[1]) * 16;
     }     
    }
 
      analogWrite(red, r);
      analogWrite(green, g);
      analogWrite(blue, b);
 
      pointer = 0;      
      }
 
      delay(100);
}
 
// convert on HEX characeter into decimal number
int hex2dec(byte c) {
  if (c >= '0' && c <= '9') {
    return c - '0';
  } else if (c >= 'A' && c <= 'F') {
    return c - 'A' + 10;
  }
}

arduino ide menubar
Fire up the Arduino IDE and paste this in. Hit Command+U (or the menu equivalent) to upload the sketch to the board. Now click the serial monitoring button (it’s the one all the way to the right). This will let you send and receive serial messages. Try sending #0FF. The board should light up the first blue LED all the way to full brightness. Try #1FF and #2FF. If those work then you’re good to go.

Now comes the Facebook stuff. This part takes the longest. Sign into facebook (of course you have an account) and go to http://developer.facebook.com/. Create a new app, just follow the wizard steps (you can name it anything). Then write down your API_KEY and SECRET_KEY. They’ll be used quite a bit below.

First, we need to get an infinite session key from Facebook. I found some code online that gets part of the way there but it was extremely confusing as to what to do with it. It took me many hours to realize that what is returned by this class is the infinite session key.

Go to the main method below and change API_KEY, SECRET_KEY and AUTH_TOKEN_HERE. Compile this code with javac (or in Eclipse). Now run it. It will return a raw http response with a session element in it. It will be a long hash type value. Copy this, this is the infinite session key.

Infinite session key code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
/* 
 * Web Site: http://as-m-going-on.blogspot.com/2010/05/tiny-java-connector-for-facebook.html
 * Author: Prasanta Paul 
 *---------------------------------------------- 
 *Command Line Option 
 *-Dhttp.proxyHost=your.proxy.dom -Dhttp.proxyPort=XX 
 *----------------------------------------------- 
 * TODO: Write a wrapper for HTTP Post 
 * TODO: XML Parser to parse API output 
 */
package com.excoflare.facebook;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Date;
 
public class FBAgent {
	private URL FB_URL = null;
	private String SECRET;
 
 
	private String apiReqParms[] = null;
	private int parmIndex = 0;
 
	public FBAgent(int numParms) {
		try {
			parmIndex = 0;
			apiReqParms = new String[numParms];
			FB_URL = new URL("http://api.facebook.com/restserver.php");
		} catch (Exception ex) {
			printLog("Error: " + ex.toString());
			ex.printStackTrace();
		}
	}
 
	public void setAPISecret(String secret) {
		this.SECRET = secret;
	}
 
	public void addAPIParm(String key, String value) {
		apiReqParms[parmIndex++] = (key + "=" + value).trim();
	}
 
	public void sendHTTPRequest() throws Exception {
		String reqParms = "";
		for (int i = 0; i < apiReqParms.length; i++) {
			reqParms += apiReqParms[i];
			reqParms += "&";
		}
		// Add Signature
		reqParms += "sig=" + genSig();
		printLog("Data to Reg=" + reqParms);
		if (FB_URL == null) {
			printLog("Empty URL....");
			return;
		}
		HttpURLConnection conn = (HttpURLConnection) FB_URL.openConnection();
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		conn.connect();
 
		// Send Request Parameters
		printLog("Sending Request Parameters...");
		OutputStream out = conn.getOutputStream();
		out.write(reqParms.getBytes());
		out.flush();
 
		printLog("Response Code=" + conn.getResponseCode());
 
		printLog("Get Response...");
		BufferedReader rd = new BufferedReader(new InputStreamReader(conn
				.getInputStream()));
		String line;
		StringBuffer outputData = new StringBuffer();
		while ((line = rd.readLine()) != null) {
			// Process line...
			outputData.append(line);
			printLog(line);
		}
 
		out.close();
		rd.close();
 
	}
 
	public String genSig() {
		try {
			// Sort Alphabetically
			Arrays.sort(apiReqParms, String.CASE_INSENSITIVE_ORDER);
			String reqParmsStr = "";
 
			// Concate
			for (int i = 0; i < apiReqParms.length; i++) {
				reqParmsStr += apiReqParms[i];
			}
			reqParmsStr += this.SECRET;
			printLog("Sig Input=" + reqParmsStr);
			// Get MD5 Hash
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(reqParmsStr.getBytes());
			byte keyB[] = md.digest();
			printLog("Key=" + new String(keyB));
			printLog("Key-UTF=" + URLEncoder.encode(new String(keyB), "UTF-8"));
			return getHexCode(keyB);
		} catch (Exception ex) {
			printLog("Error in Generating Signature: " + ex.toString());
		}
		return "";
	}
 
	public String getHexCode(byte byteA[]) {
		byte dig = 0;
		char hexCode[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };
		// Capital doesn't work
		String hexVal = "";
		byte msn, lsn;
		for (int i = 0; i < byteA.length; i++) {
			dig = byteA[i];
			msn = (byte) ((dig >> 4) & 0x0F);// Most Significant Nibble
			lsn = (byte) (dig & 0x0F);// Least Significant Nibble
			hexVal = hexVal + hexCode[msn] + hexCode[lsn];
		}
		return hexVal;
	}
 
	public void printLog(String msg) {
		System.out.println(msg);
	}
 
	public static void main(String args[]) {
		/*
		 * -------------------------------------------- Auth.createToken
		 * fb.addAPIParm("api_key", fb.API_KEY); fb.addAPIParm("method",
		 * "auth.createToken"); fb.addAPIParm("v", "1.0");
		 * --------------------------------------------
		 */
		try {
			FBAgent fb = new FBAgent(4);
			fb.setAPISecret("SECRET_KEY_GOES_HERE");
			fb.addAPIParm("api_key", "API_KEY_GOES_HERE");
			// Get auth_token from http://www.facebook.com/code_gen.php?v=1.0&api_key=API_KEY
			fb.addAPIParm("auth_token", "AUTH_TOKEN_HERE");
			fb.addAPIParm("method", "auth.getSession");
			fb.addAPIParm("v", "1.0");
			fb.sendHTTPRequest();
		} catch (Exception ex) {
			System.out.println("Error:" + ex.toString());
			ex.printStackTrace();
		}
	}
}

Now take your API_KEY, SECRET and AUTH (infinite session key) and put them into the below Processing code. Also change the Serial.list()[2] line to be your serial port. On mac, you need to install the usb to serial driver included with the Arduino IDE folder.

Processing code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import processing.serial.*;
 
import com.google.code.facebookapi.*;
import org.json.*;
 
FacebookJsonRestClient facebook;
 
int interval = 10; // retrieve every 10 seconds
int lastTime;
 
// 3 Facebook IDs to watch
int[] ids = {  515470367,  // patton oswalt
               26670531942,  // mccoy tyner
              508305963}; // hugh mcleod
 
Serial port;
 
// Customize setup to fit your environment
void setup() {
  frameRate(10);
 
  String apiKey = "CHANGETHIS"; // your api key
  String secretKey = "CHANGETHIS"; // your secret
  String sessionKey = "CHANGETHIS";  // infinite session key goes here
  facebook = new FacebookJsonRestClient(apiKey,secretKey,sessionKey);
 
  // 
  String arduinoPort = Serial.list()[2];
  port = new Serial(this, arduinoPort, 9600); // connect to Arduino
 
}
 
 
 
void draw() {  
  int n = (interval - ((millis()-lastTime)/1000));
 
  if (n <= 0) {
 
    for (int i = 0; i <= 2; i++) {
      int uid = ids[i];
      String userStatus = fetchData(uid);
 
      /* light up arduino based on facebook status
         facebook API says: 
         online_presence string	 The user's Facebook Chat status. Returns a string, 
         one of active, idle, offline, or error (when Facebook can't determine presence
         information on the server side). The query does not return the user's Facebook
         Chat status when that information is restricted for privacy reasons.
         */
      if (userStatus.equals("active")) {
        sendSerial("#" + i + "FF");
      }
      if (userStatus.equals("idle")) {
        sendSerial("#" + i + "10");
      }
      if (userStatus.equals("null")) {
        sendSerial("#" + i + "00");
      }
      if (userStatus.equals("offline")){
        sendSerial("#" + i + "00");
      }
      if (userStatus.equals("error")){
        sendSerial("#" + i + "00");
      }
 
    }
 
    lastTime = millis();
 
 
  }
}
 
String fetchData(int uid) {
      try {
        String query = "SELECT name FROM user WHERE uid=" + uid;
        JSONArray resultArray = (JSONArray)facebook.fql_query(query);
        JSONObject result = resultArray.getJSONObject(0);
        print("Querying online status of " + result.getString("name") + ": ");
 
 
        query = "SELECT online_presence FROM user WHERE uid=" + uid;
        resultArray = (JSONArray)facebook.fql_query(query);
        result = resultArray.getJSONObject(0);
        String userStatus = result.getString("online_presence");
        println(userStatus);
        return userStatus;
 
} catch (Exception jex) {
  jex.printStackTrace();
}
return "";
}
 
void sendSerial(String message) {
  port.write(message);
}

Save this sketch but don’t run it yet. We’re missing some libraries.

Libraries for the facebook java lib need to go under: ~/Documents/Processing/libraries/facebook/library. I had the following jars in that folder. The json jar

activation-1.1.jar jaxb-api-2.1.jar
commons-logging-1.1.1.jar jaxb-impl-2.1.3.jar
facebook-java-api-schema-2.0.4.jar json-20070829.jar
facebook.jar stax-api-1.0-2.jar

All of these jars should come from the Google Code project I liked at the beginning of this post. After all these things are ready, get the arduino running and then run your Processing sketch.

facebook arduino processing client
It should pop up the default Processing window. There’s nothing sexy about this app. It has no GUI and writes simple status lines to the console. It will run until this window is closed. Every 10 seconds it should update the LEDs with the status from Facebook. I’ve found that the status isn’t always real-time. But it’s close enough for our purposes. You can change the IDs to monitor in the Processing code. The IDs can be found on Facebook by looking at someone’s profile. For example, Patton Oswalt’s profile page is http://www.facebook.com/profile.php?id=515470367. His ID is 515470367.

Conclusion

It was a fun little project. I’m glad I got it working in my time off from work. It took me about 6 hours straight and I was really in the zone at the end (1:15am). The facebook bits took me almost 4 hours just because of the lack of documentation about that freaking infinite session key. There are a lot of examples on the web on Java in a web container (or PHP) but very few desktop app examples.

Please let me know if you found this interesting, attempted it, ran into problems, have suggestions for improvements or anything else by leaving a comment.

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License.
(c) 2012 SQUARISM | powered by WordPress with Barecity