Feedback!

Tweetheart Twitter to Arduino

Views: 5802 Difficulty: 4 Status: Development
Tweetheart

Using twitter4j, processing, and the serial port, load twitter feeds in arduino.

Make your Arduino tweet with this tutorial. We show how to connect a processing sketch to twitter and the serial port, allowing you to receive tweets on an Arduino, which you can display on our heart matrix, or wherever you like! We will use the awesome twitter4j library (download the latest stable version zip file). This tutorial is based on the great explanation at blprnt.com, with some tweaks to include an Arduino on a serial port, the latest syntax for the twitter4j library, and updated instructions for the ever-evolving twitter API.

Tweeting to the Heart Matrix

Tweetheart
Tweet to the heart matrix. Grab feeds, or hashtags that have been indexed on twitter, and print them out in LED dot matrix text.

Step-by-Step Instructions

Step 0 Download twitter4j

Download the twitter4j library and bring it into a processing sketch. You can load it into your processing sketch by unzipping the download file and navigating to the lib folder. In there you will find the jar (java archive) files that make up the library. For now, all you need is the file named twitter4j-core-3.0.3.jar. If you get more intimate with twitter4j you may need to load those other libraries for more functionality. If you have a processing sketch open you can load the library by just dragging and dropping the jar file onto the open sketch window. You can check it worked by finding a new folder named code inside the processing sketch folder. Inside the code file lives the jar library file. You can manually create this folder and put the jar file in it if you do not wish to use the drag and drop technique. Note: At the time of writing the version is 3.0.3, but this is bound to change, just substitute the current version number for 3.0.3 and you should be fine, until the make major modifications to the library :p .

Step 1 Get Twitter Credentials!

This step is necessary because twitter beefed up their security. You used to be able to access the twitter API by just providing a password and a username. Nowadays, you need some credentials-- Heres how to get them. First, login to twitter and go to twitter's developer create application page. Click the "Create Application" button. Fill out the form on the following page, supplying your name, app description, website, and callback url (leave it blank if you're unsure). Figure out the practically indecipherable captcha and click the "Create your Twitter Application" button, and hope. If you got the form right, you have now created your very own twitter application! The next page offers your oAuth settings. Take note of your consumer key and and your consumer secret, as you will need these in the processing sketch. Now click the "create my access token" button and you should get the final bits of data that we need. Take note of the Access token and Access token secret fields.

Step 2 Put it together in Processing.

Grab the code below and paste in the four values (Consumer Key, Consumer Secret, Access Token, and Access Token Secret) in the get_tweet function where we set up the configuration builder.
  cb.setOAuthConsumerKey("yourconsumerkey");
  cb.setOAuthConsumerSecret("yourConsumerSecret");
  cb.setOAuthAccessToken("yourAccessToken");
  cb.setOAuthAccessTokenSecret("yourAccessTokenSecret");
Try running the program. You should see the word hello scrolling across the screen. Now click the mouse on the sketch. Does the word hello change? Did you grab a tweet?! If so, congrats you're on your way! Otherwise, double check that you got the right keys and access tokens in the right place. Make sure you imported the twitter4j library into your sketch and that you have an internet connection. Make sure there are tweets indexed to you current search term. The search term is whatever is in quotes in the line:
Query query = new Query("#HeartMatrix");

Step 3 Grab the tweet from the Serial Port on an Arduino

Now that we have our processing sketch running the last step is to connect an arduino on the serial port to receive the tweet being sent by the Processing sketch. Make sure to select the right serial port in these lines in the setup function
  String portName = Serial.list()[0];
  myPort = new Serial(this, portName, 9600);
Change the 0 to whichever port you want to use. All the ports are listed on the console by the previous line in the setup function. Now on the Arduino side of things, you will need to listen to the Serial port and store what it sends you in a String variable. This is the code to do just that:
while (Serial.available() ){
     char c = Serial.read();
     if (c == 8) message = "";
     else {
       String s = String(c);
       message += s;
       hm.set_message(message);
     }
  } 
Check out the whole Arduino code file below. We show how to use it with our heart matrix, but you could grab the tweet and parse it to control a robot, lights, or a motor. Let your imagination go twitter crazy!

Processing Sketch Twitter Api to the Serial Port

This processing code grabs tweets and spits them out the serial port, as well as scrolling them across the screen. Currently it loads any tweet indexed by twitter with hash tag "#heartmatrix", but you can change that to whatever you like. Following the steps detailed above you should keys and tokens you need for the configuration builder. The ones included in this code will not work for you. The heart of the code is the function get_tweet()
String get_tweet(){
  String a_tweet = "";
  ConfigurationBuilder cb = new ConfigurationBuilder();
  cb.setOAuthConsumerKey("yourconsumerkey");
  cb.setOAuthConsumerSecret("yourConsumerSecret");
  cb.setOAuthAccessToken("yourAccessToken");
  cb.setOAuthAccessTokenSecret("yourAccessTokenSecret");
  Twitter twitter = new TwitterFactory(cb.build()).getInstance();
  
  Query query = new Query("#HeartMatrix");
 
  try {
    QueryResult result = twitter.search(query);
  }
  catch (TwitterException te) {
    println("Couldn't connect: " + te);
    a_tweet = "No Tweet Found :(";
  };
  
  query.setCount(100);
 
  try {
    QueryResult result = twitter.search(query);
    ArrayList tweets = (ArrayList) result.getTweets();
    if (tweets.size() > 0 ){
      Status t = (Status) tweets.get(0);
      String user = t.getUser().getScreenName();
      a_tweet = t.getText();
      Date d = t.getCreatedAt();
      println("Tweet by " + user + " at " + d + ": " + cur_tweet);
    } else  a_tweet = "No Tweet Found :(";
  }
  catch (TwitterException te) {
    println("Couldn't connect: " + te);
    a_tweet = "Twitter Exception :(";
  }; 
  return a_tweet;
}
If nothing can be found or the credential don't work, we just set the return text to "Twitter Exception :(" or "No Tweet Found :(" so you don't have to do any error-catching. You can grab much more than just a tweet, but that is all we needed for our project. Check the twitter4j documentation for more capabilities. So every time the mouse is pressed we query twitter for more tweets. We grab the first one and compare it to the current one. If it is a new tweet, we send it out on the serial port and update the cur_tweet variable. This all happens in the check twitter function:
void check_twitter(){
  String new_tweet = get_tweet();
  if (!new_tweet.equals(cur_tweet)){
    cur_tweet = new_tweet;
    myPort.write(8);
    for (int i = 0; i < cur_tweet.length(); i++){
      myPort.write(cur_tweet.charAt(i)); 
    }
  }
}
Careful about checking twitter too frequently, like in the the draw loop, for example, they may start to think you are spamming them.
/*  LucidTronix Processing sketch
 *  Twitter API to the serial port
 *  for more info see the tutorial at:
 *  http://www.lucidtronix.com/tutorials/32
*/

import processing.serial.*;
import java.util.*;
Serial myPort;  // Create object from Serial class
int val;        // Data received from the serial port
//Build an ArrayList to hold all of the words that we get from the imported tweets
ArrayList<String> words = new ArrayList();
String cur_tweet = "Hello";
int cur_x = 600;
int last_check = 0;
void setup() 
{
  size(600, 600);
    
  // I know that the first port in the serial list on my mac
  // is always my  FTDI adaptor, so I open Serial.list()[0].
  // On Windows machines, this generally opens COM1.
  // Open whatever port is the one you're using.
  println(Serial.list());
  String portName = Serial.list()[0];
  myPort = new Serial(this, portName, 9600);


}

void draw() {
  //Draw a faint black rectangle over what is currently on the stage so it fades over time.
  background(0);
  fill(40,205,50); 
  text(cur_tweet, cur_x, 150);
  cur_x -= 2;
  if ( cur_x < -1*textWidth(cur_tweet )) cur_x = width;
  //if (millis() - last_check > 3000) check_twitter;
  
}
void mousePressed(){
  check_twitter();
}
void check_twitter(){
  String new_tweet = get_tweet();
  if (!new_tweet.equals(cur_tweet)){
    cur_tweet = new_tweet;
    myPort.write(8);
    for (int i = 0; i < cur_tweet.length(); i++){
      myPort.write(cur_tweet.charAt(i)); 
    }
  }
  
}
String get_tweet(){
  String a_tweet = "";
  ConfigurationBuilder cb = new ConfigurationBuilder();
  cb.setOAuthConsumerKey("yourconsumerkey");
  cb.setOAuthConsumerSecret("yourConsumerSecret");
  cb.setOAuthAccessToken("yourAccessToken");
  cb.setOAuthAccessTokenSecret("yourAccessTokenSecret");
  Twitter twitter = new TwitterFactory(cb.build()).getInstance();
  
  Query query = new Query("#HeartMatrix");
 
  try {
    QueryResult result = twitter.search(query);
  }
  catch (TwitterException te) {
    println("Couldn't connect: " + te);
    a_tweet = "No Tweet Found :(";
  };
  
  query.setCount(100);
 
  try {
    QueryResult result = twitter.search(query);
    ArrayList tweets = (ArrayList) result.getTweets();
    if (tweets.size() > 0 ){
      Status t = (Status) tweets.get(0);
      String user = t.getUser().getScreenName();
      a_tweet = t.getText();
      Date d = t.getCreatedAt();
      println("Tweet by " + user + " at " + d + ": " + cur_tweet);
    } else  a_tweet = "No Tweet Found :(";
  }
  catch (TwitterException te) {
    println("Couldn't connect: " + te);
    a_tweet = "Twitter Exception :(";
  }; 
  return a_tweet;
}

Arduino Code to Read String from the Serial Port

This Arduino code displays text from the serial port onto our heart matrix display. Every time the ascii code for delete (decimal: 8, binary: 00001000) is received the message string is cleared. Otherwise, every character received from the serial port is appended to the message string variable. The code to read from the Serial port is the following while loop:
while (Serial.available() ){
     char c = Serial.read();
     if (c == 8) message = "";
     else {
       String s = String(c);
       message += s;
     }
  }
This code uses our heart matrix library, as well as the frequencyTimer2 library.
/* LucidTronix write messages from
 * the serial port on the Heart Matrix.
 * For instructions details and schematic, See:
 * http://www.lucidtronix.com/tutorials/18
 * For details on connecting with twitter, See:
 * http://www.lucidtronix.com/tutorials/32
 * Connect the data, latch, and clock pins
 * to the corresponding pins on the heart matrix
 */
#include <FrequencyTimer2.h>
#include <HeartMatrix.h>
String message = " Hi!";
// In is on 5, Latch is on 6, and Clock is on 7
HeartMatrix hm = HeartMatrix(5,6,7);
void displayer2(){  
  hm.displayer();
}
void setup() {
   FrequencyTimer2::disable();
   // Set refresh rate (interrupt timeout period)
   // if things break try making this number bigger
   FrequencyTimer2::setPeriod(2000);
    // Set interrupt routine to be called
   FrequencyTimer2::setOnOverflow(displayer2); 
   hm.set_message(message);
   Serial.begin(9600);
}
void loop() {
   hm.on();    
   while (Serial.available() ){
     char c = Serial.read();
     if (c == 8) message = "";
     else {
       String s = String(c);
       message += s;
       hm.set_message(message);
     }
  } 
}

Parts

Title Description # Cost Link Picture
Heart Matrix Kit The heart matrix kit. Shift register based wearable heart-shaped LED display. 1 $17.95 Link Heart_matrix_baggy
Permalink: http://lucidtronix.com/tutorials/32
Control the Heart Matrix LED display wirelessly, using XBEE radio modules....
Combine an electret microphone, Arduino and a heart matrix for a sound-sensitive wearable device....
Connecting the DS1307 real-time clock chip and our Heart Matrix you can show the time with love....
The heartduino is a heart-shaped arduino clone complete with onboard sensors and a 70 pixel LED matri...
Standalone programmable Heart-Shaped LED display....
Two LED matrices give 70 LEDs to light up a necklace with messages....
Shift Registers help you multiply your inputs and outputs....
4 Daisy chained CD4021 shift registers gives us 32 inputs....