Twitter to Arduino Hack!

(This Post is a class requirement for History 9832b Interactive Exhibit Design)

I have to say, this project has been a tough slog!  As discussed in previous blog’s, there are a lot of Twitter to Arduino hacks out there, but each has their own very specific approaches, which at times are hardware and/or software dependent.  Further I’ve learned that I’m a purely visual learner when it comes to physical objects or coding, which means I need to see someone do it first before I can really pick up on the process……..helpful for learning how to chop wood ; )

Luckily I ran into a great chap who teaches at Ryerson by the name of Nick Stedman (http://www.nickstedman.com/).  Oddly enough he was teaching a class last week in Arduino to Twitter through processing and invited me to sit along.  Below is what I think is a very useful approach to having Twitter control Arduino, but explained in a simple way.

So Nick had us work with a hack I had tried previously from Jer @ blprnt (http://blog.blprnt.com/blog/blprnt/updated-quick-tutorial-processing-twitter).  This one needs a user defined API from dev.twitter.com to generate “tokens” that will allow the Processing code to access Twitter more securely.  It also requires you to import the Twitter4J Core, which you can get here (http://twitter4j.org/en/index.html).  The part that Jer didn’t supply was the Arduino hack to read the Twitter feed from Processing and then to Arduino.

Processing Hack

So let’s start with Jer’s modified Processing code:

//Build an ArrayList to hold all of the words that we get from the imported tweets
//Needs SerialStandard for Arduino
ArrayList<String> words = new ArrayList();

import processing.serial.*;

Serial my_port;                          // Create object from Serial class
int rx_byte;                             // Variable for data received from the serial port

void setup() {
//Set the size of the stage, and the background to black.
size(200, 200);
background(0);
smooth();

String portName = Serial.list()[0];
println(Serial.list());
my_port = new Serial( this, portName, 9600 );

//Credentials – YOU NEED TO HAVE GENERATED TWITTER API TOKENS FIRST FOR THIS TO WORK –
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey(“YOUR TWITTER API CONSUMER KEY”);
cb.setOAuthConsumerSecret(“YOUR TWITTER API CONSUMER SECRET”);
cb.setOAuthAccessToken(“YOUR TWITTER API ACCESS TOKEN”);
cb.setOAuthAccessTokenSecret(“YOUR TWITTER TOKEN SECRET”);

//Make the twitter object and prepare the query – YOU NEED TO HAVE IMPORTED THE TWITTER 4J LIBRARIES FOR THIS TO WORK –
Twitter twitter = new TwitterFactory(cb.build()).getInstance();

  Query query = new Query(“Hi”);
  query.setRpp(10);

//Try making the query request.
try {

//Status status = twitter.updateStatus(“Processing to Arduino Now”); //message needs to change per tweet

QueryResult result = twitter.search(query);
ArrayList tweets = (ArrayList) result.getTweets();

for (int i = 0; i < tweets.size(); i++) {
Tweet t = (Tweet) tweets.get(i);
String user = t.getFromUser();
String msg = t.getText();
Date d = t.getCreatedAt();
println(“Tweet by ” + user + ” at ” + d + “: ” + msg);

//Break the tweet into words
String[] input = msg.split(” “);
for (int j = 0;  j < input.length; j++) {
//Put each word into the words ArrayList
words.add(input[j]);
}
};
}
catch (TwitterException te) {
println(“Couldn’t connect: ” + te);
};
}

void draw() {
//Draw a faint black rectangle over what is currently on the stage so it fades over time.
fill(0, 25);
rect(0, 0, width, height);

//Draw a word from the list of words that we’ve built
int k = (frameCount % words.size());
String word = words.get(k);

  if (word.equals(“Hi”) == true) {
    my_port.write(255);
    delay(4);    
    my_port.write(0);
  }

if (k == words.size()-1) {
    println(“new query”);
    delay(1000);

//Credentials – YOU NEED TO HAVE GENERATED TWITTER API TOKENS FIRST FOR THIS TO WORK –
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey(“YOUR TWITTER API CONSUMER KEY”);
cb.setOAuthConsumerSecret(“YOUR TWITTER API CONSUMER SECRET”);
cb.setOAuthAccessToken(“YOUR TWITTER API ACCESS TOKEN”);
cb.setOAuthAccessTokenSecret(“YOUR TWITTER TOKEN SECRET”);

//Make the twitter object and prepare the query
Twitter twitter = new TwitterFactory(cb.build()).getInstance();

Query query = new Query(“Hi”);
query.setRpp(10);

//Try making the query request.
try {

//Status status = twitter.updateStatus(“Processing to Arduino Now”); //message needs to change per tweet

QueryResult result = twitter.search(query);
ArrayList tweets = (ArrayList) result.getTweets();

for (int i = 0; i < tweets.size(); i++) {
Tweet t = (Tweet) tweets.get(i);
String user = t.getFromUser();
String msg = t.getText();
Date d = t.getCreatedAt();
println(“Tweet by ” + user + ” at ” + d + “: ” + msg);

//Break the tweet into words
String[] input = msg.split(” “);
for (int j = 0;  j < input.length; j++) {
//Put each word into the words ArrayList
words.add(input[j]);
}
};
}
catch (TwitterException te) {
println(“Couldn’t connect: ” + te);
};
}
}

With the Twitter 4J Libraries installed in your Processing Sketch you should be able to run this and get a constant print in the Sketch’s terminal.

This code searches for the query word and sets it’s query search to 10 returns or examples:

Query query = new Query(“Hi”);
  query.setRpp(10);

This code sends to the serial port that connects with Arduino, that if we find a query word, then == true, which then sends a value of 255 or fully “on” then delay by a value of 4 and turn off sent value.  Basically, if “Hi” is Tweeted, then send to the Arduino that value as positive and turn on the LED fully.  After 4 seconds, turn off the LED and wait for next value.

  if (word.equals(“Hi”) == true) {
    my_port.write(255);
    delay(4);    
    my_port.write(0);
  }

This code and everything repeated below it asks the Processing Sketch to do another query for “Hi” constantly.

if (k == words.size()-1) {
    println(“new query”);
    delay(1000);

The Hack that Nick suggested is that to initialize the query, we have to set it first, return the initial value and then the same code has to be added again to ensure that the query runs continuously looking for the value or query word “Hi”.

Arduino Sketch

Additionally to get the Arduino LED to light, you need the Arduino Sketch, which was the missing piece in the Jer example above.

// Very basic program to try out serial communication.
// Checks for data on the serial port and dims an LED proportionally.
// Then reads a sensor, and transmits the value.
// NB. Serial is limited to one byte per packet, so constrain the data you communicate to 0-255.

int led_pin = 9;                           // use “led_pin” to reference pin #
int rx_byte;                             // a variable for receiving data
int sense;                               // a variable for storing sensor data
void setup()
{
Serial.begin( 9600 );                  // start serial port at this speed (match with other software eg. MAX, Processing)
pinMode( led_pin, OUTPUT );                  // make pin an output – connect to LED (remember to use => 220ohm resistor)
}
void loop()
{
if( Serial.available() > 0 ) {         // if we receive a byte:
rx_byte = Serial.read();             //   store it,
analogWrite( led_pin, rx_byte );      //   and dim LED according to its value
}
sense = analogRead( 0 );               // read the sensor – returns 0 to 1023
sense = map( sense, 0,1023, 0,255 );   // adjust values to transmit – scale to 0 to 255 (…dividing sense by 4 would do the same)
Serial.write( sense );    // send the sensor data
//  Serial.write( sense );        // use this command instead for new Arduino version
delay(10);
}

This Arduino Sketch is really just reading data from Processing and sending it to the Arduino unit to turn the LED off and on based on how many times the Twitter keyword is found.

Conclusions

Here is yet another example of how to extract data from Twitter.  Like the post previously we now have two methods of accessing Twitter through Processing.  The first method is a straight query, using your Twitter Log-in and Password.  The second as described above, increases the security to your Twitter access by using the Twitter API function to generate secure tokens.

Although Nick’s method is a great first step, we still need to regulate how the Twitter query feeds into Processing and then Arduino.  Right now it’s a massive dump of info.  With the additional code to repeat the query, we’re still getting the same results + new results in every query, so we need to ensure that for every one tweet, it only returns it’s value once to Arduino.  Then we can use that one value return to inch our step motor and flag up the pole.

2 thoughts on “Twitter to Arduino Hack!

  1. I’ve been trying to do something similar. I want an LED connected to Arduino to blink whenever someone uses the hashtag #bikehugger. I have my wifi/Arduino figured out and can get it connected to the internet… I have the LED set up… I just need ot figure out the code or find someone that has done this…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s