Huston we have tweet-off.

Sort of unsettlingly the twitter code doesn’t touch the Arduino. As I’ve had to use Processing we will connect with the sensors and actuators using Firmata. It’s cool, and certainly with how Twitter has made checking tweets such a pain it is logical, it just feels a bit weird since this is being made for a Physical Computing course! The part for checking tweets is a modification of the code found here.

Anyway, here is the code (sans Firmata for now) for checking tweets and sending out a tweet in response using Twitter4j:

import twitter4j.conf.*;
import twitter4j.*;
import twitter4j.auth.*;
import twitter4j.api.*;
import java.util.*;

Twitter twitter; //twitter instance
String searchString = “#getRollingMrBall”; //hashtag to search for
List<Status> tweets; //list of tweets

int currentTweet; //int to hold the current number of tweets
int runsDone = 0; //how many times has the run function completed

void setup()
ConfigurationBuilder cb = new ConfigurationBuilder();
//add all the keys necessary for Twitter authentication

TwitterFactory tf = new TwitterFactory(; //use authentication

twitter = tf.getInstance(); //pass twitter factory to the instance of twitter

getNewTweets(); //check for all current tweets containing the search query

currentTweet = tweets.size(); //this stops the run starting from preexisting tweets

thread(“refreshTweets”); //refresh tweets is run in a seperate thread, evert 30 seconds it calls getNewTweets

void draw()
//All’s quiet on the drawing front

void getNewTweets()
try //try catch because the internet is a risky place
Query query = new Query(searchString); //add the string to be matched to the query

QueryResult result =; //query twitter

tweets = result.getTweets(); //store the results in an array list
catch (TwitterException te)
System.out.println(“Failed to search tweets: ” + te.getMessage());
System.exit(-1); //exit on fail

void refreshTweets()
while (true) //just keep running
getNewTweets(); //check for new tweets

println(“Updated Tweets”);

if(tweets.size() > currentTweet){ //there is a new tweet!
println(“new tweet received”);
sendTweet(); //send a tweet in response
currentTweet = tweets.size(); //mark the new size of matching tweets
println(“Current matching tweets = ” + currentTweet);
delay(30000); // Mustn’t request information too often

void sendTweet(){
try {
runsDone++; //called again
String t = “Just completed run number ” + runsDone + “! (Runs count since I last booted up)”;//make up the string to tweet
Status status = twitter.updateStatus(t); //update the status with the above string
println(“Successfully updated the status to [” + status.getText() + “].”);
} catch(TwitterException e) { //print error code if update fails
println(“Send tweet: ” + e + ” Status code: ” + e.getStatusCode());