Introduction: Twitter Monitoring Toy Built With LEGO & Arduino

About: Technology is subversive.

This is an animated LEGO toy which monitors twitter and celebrates each time it finds a new occurrence of the hashtag #BLOCKSHELL by sounding a bell, flashing a light, and sending a little minfigure activist dude up the superstructure of an Arctic oil rig.

(The minifig dude is celebrating because he agrees LEGO should be filling kids heads with inspiration and ingenuity rather than making oil companies that are wrecking the planet look good.)

Step 1: Twitter Monitoring LEGO Toy With Arduino

At the heart of this toy was an idea that I wanted to:

1) Watch twitter for something
2) Make some noise and movement when that something happens

This probably could have been done with a single PHP or Python script rather than my hodge-podge of shell scripts and an Applescript, but as I tried to put it together fast, over a weekend, this is where the combination of reusing what I could find and the limits of my code skills ended up hacking together.

I have both an Arduino Uno and a Leonardo. I chose Leonardo for this project because it handles monitoring serial communications via the USB port, and the Uno doesn't. I've not yet splashed out for a WIFI Shield or an ehternet shield, so I needed something that would be able to interact with the internet via the laptop attached via USB. With onboard internet, you could make a more independent toy.

What you'll need:

Macbook Pro or other OSX based computer
Arduino Leonardo or similar (make sure it can handle Serial communications on the USB)

Electric Motor (one that will run on a 5 volt source)

NPN Transistor
100 Ohm resistor (Or thereabouts)

Optional: For the particular toy I made, I used the following kits:
Snap Circuits
Connex 125 Scientific Challenge Set

Step 2: The Twitter Monitoring Engine & Bash Scripts

I built the Twitter monitoring engine with T -- a command line interface written by Erik Michaels-Ober (@Sferik on Twitter). The instructions for installing T are here. If you've never installed a twitter app and gotten authorisation tokens, this step can be a bit daunting. Stick with it! Erik has provided a great set of step-by-step instructions, and T is an amazingly useful tool which allows you to do some programmatically useful things with Twitter from the command line of your Mac, and so allows you to automate a ton of stuff.

Once you have T installed, you want to test the following command:

t search all  "#YOUR_TARGET_TEXT"  -n 1 -l > lasttweet.txt

That should search Twitter for #YOUR_TARGET-TEXT and write the tweet to a file called lasttweet.txt

Now put that in a Bash script, I called mine and put it in my /var/www directory:

#! /bin/bash<br>t search all "#BlockShell" -n 1 -l > /var/www/lasttweet.txt

(If you don't know how to write Bash Scripts, or want a freshen up, here's a great tutorial)

You'll call that script to execute from your AppleScript in a bit.

Step 3: The Script to Write to the Serial Port

But while you're on the command line, we'll need one other Bash script to alert the Arduino via the Serial Port that we've found a tweet. It's also a two line script, simply writing a character, in this case "V" (for victory) to the USB serial port that the Arduino is plugged into:

#! /bin/bash <br>echo -en "V" > /dev/tty.usbmodemXXXX

Replace XXXX with the number of the port your Arduino is on. You'll see that in the lower right hand corner of the Arduino interface.

Step 4: The Applescript

(Psst. For this project I brushed up on my Applescript Basics at the tutorial here)

This simple script reads the contents of lasttweet.txt (which was created by your script) into a variable called "OldTweet," calls and so writes anew to lasttweet.txt. We read those contents into a variable called "NewTweet" and compare "OldTweet" and "NewTweet". If they're the same, do nothing and loop back to the beginning. If they're different, call to send the letter "V" to the serial port to alert the Arduino there's a new tweet.

To keep any humans that might be watching entertained, pop the tweet into a dialog window for them to read. The dialogue box gives you an opportunity to cancel the script if you want, but it will also give up waiting for input after four seconds so the script can carry on unattended. By the way, that dialog is embedded in a 5 second time out call to Finder simply to avoid a bug (though some call it a feature) in the Display Dialog command which will timeout the entire script without it, even though you tell the dialog to give up after 4 seconds.

The delay of 20 ensures that T doesn't annoy twitter with too many API calls. It's probably too long, but I'm a coward about annoying the Twitter Gods... :-)

	set OldTweet to " "
	set NewTweet to " "
	set theFile to "/var/www/lasttweet.txt" as «class utf8»
	set OldTweet to do shell script "cat " & "/var/www/lasttweet.txt"
	do shell script "/var/www/"
	set NewTweet to do shell script "cat " & "/var/www/lasttweet.txt"
	if OldTweet is equal to NewTweet then
		do shell script "/var/www/"
		tell application "Finder"
			with timeout of 5 seconds
				display dialog "New Tweet: " & NewTweet giving up after 4
			end timeout
		end tell
	end if
	delay 20
end repeat

Step 5: The Arduino Script

This script runs an LED off Pin 13 and the two motors (one for a bell, one which makes the little minifig activist dude go up and down) off a transitor circuit connected to pin 9. The script just sits and monitors the serial port, and sets those pins high if it receives the character "V" from the Applescript.

<p>// give the inputs a name:<br>int led = 13;
int motorPin = 9;
int count = 0;
void setup() {
  // Open serial communications and wait for port to open:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
    // initialize the digital pin as an output.
  pinMode(led, OUTPUT); 
  pinMode(motorPin, OUTPUT); 
  }</p><p>  // send an intro:
  Serial.println("I'm waiting for the Applescript to send me the character 'V'");
}</p><p>void loop() {
  // get any incoming bytes:
  if (Serial.available() > 0) {   //Hey, something's come in the serial port!
    char inChar = (char); //Let's read it to the inChar variable
    if (inChar == 'V')  { //Let's make sure it's the one we're wating for, "V"
     digitalWrite(motorPin, HIGH); //Turn the motor on by setting voltage high
     digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(2000);               // wait for a second
  count = count + 1;
  Serial.print("Hit # "); //Useful for debugging. This writes to the output window
  digitalWrite(motorPin, LOW);  //Turn the motor off by making the voltage LOW 
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second

Step 6: The Build

You can make a very fine Arduino encasement with LEGO & the arch bricks are great ways to channel wires. One tip, make sure you have access to the reset button on the board. You may need it!

Your toy will certainly be different from mine, so I won't take you through the particulars of how I lovingly crafted my Arctic oil rig, the joy I felt when I found plates with "Keep Out" stickers or the sheer brilliance of the gear box build. These were particular to the toys I had to hand, your mileage will vary.

I'm indebted to the folks at How to make an Arduino Spin up a Motor for Complete Dummies for charting out the circuit pictured above for running the motor off pin 9 of the Arduino.

The motor I had was designed to run on 2 AA batteries -- 6 volts, but the 5 from the Arduino is within specs. You can't start and stop the 5 volt circuit directly, you want to put that little transistor circuit in there to act like a gate. It's like a switch in the off position when there's no voltage from pin 9, so that 5 volt circuit doesn't run. Put a digital signal to the base of the transistor, however, and the current runs from collector to emitter.

The curious may wonder why that diode is backward. It's there to provide a short circuit to protect your Arduino, in the event the spinning motor generates a spurious current which might discharge after the transistor gate closes. It'll loop through the diode as the path of least resistance, rather than running to ground through your Arduino circuitry. A note on resistance: that 2.2K ohm resistor was way too much -- I tried a 1K and even then the circuit didn't fire. 100 ohm worked a treat

I built my circuit with my kids' Snap Circuits electronic kit -- it's even easier than a breadboard, and you can integrate the set with Arduino pin-outs using these handy snap-circuit to pin cables.

The motors and the bell were scavenged from a Connex modular motor kit. The crank gear that converts circular motion into linear (in this case, the little minifig activist dudes' up and down motion on the climbing rope) was a perfect fit for a LEGO 5-hole Technic Beam. And the plastic platforms that Connex provides to build their kits on can be anchored to your LEGO toy by placing the plastic base over a single row of studs on your baseplate. The motors cause wiggle, but the unit stays locked!

When you're ready to run your toy, make sure you start your Arduino script first and open that monitoring window with Shift-Command-M. This opens the serial port for writing. If you try to do the Applescript first, I've found the Arduino software can seize up -- press the reset on the board to break the deadlock, but you'll need to re-upload your code to the Arduino board.


Community Contest: Toy Building Blocks

Participated in the
Community Contest: Toy Building Blocks