Posting to Twitter with an Arduino via Processing using Twitter4j

Recently I had to teach my students how to produce a physical computing device using Arduino which was talked to Twitter. Without an ethernet or WiFi shield, the best way to accomplish this is letting an Arduino communicate with Processing over a serial connection, which then talks to Twitter. We don’t have to use Processing for anything in particular other than talking to the API. And to talk to the API we can use a library called Twitter4J. Twitter4J is an unofficial Java library for the Twitter API. With Twitter4J, you can easily integrate any Java application (or in our case a Processing sketch) with Twitter.

This tutorial will show you how to connect a couple of buttons to an Arduino and have one of them perform a Twitter search query, and the other one will tweet the current time.

Twitter4j & Twitter Account Setup

First make sure you have:
Downloaded and installed Processing
Downloaded and installed Arduino
Also grab the latest version of Twitter4J

Once it’s downloaded you have to install it in the Processing library folder.

Unzip the downloaded zip folder.
Rename the unzipped folder to “twitter4j”.
Inside this folder create a new folder called “library”.
Next look for a folder called “lib”.
Move the file called “twitter4j-core-4.0.4.jar” inside our library folder we just made.
Rename that file to “twitter4j.jar”.

Check that you have the following structure
/Processing/libraries/twitter4j/library/twitter4j.jar
Screen Shot 2016-02-25 at 12.09.51

Next you have to add a phone number to the account you want to use. I recommend making a test account just for testing out Twitter & Processing. You have to add a phone number to your account in order to use the API.
Screen Shot 2016-02-25 at 12.25.51

If it’s a UK number you might have some problems, try it with the 0, and you’ll hopefully get a text with the confirmation code. Try replying to the message and if all is good and then you should be able to tweet by texting the number. If not try it without the 0. Repeat until you have success or want to destroy the developer behind this.

Now we have to make an app! Go to apps.twitter.com/ and hit create new app (make sure you are logged in with your new shiny test account).
Screen Shot 2016-02-25 at 12.22.54

Here we have to enter some details about our new app. Give it a name and description. You can change the description later and the name doesn’t really matter as this is just a tutorial. Give it a website address if you have your own use that, or throw in the address for the profile you are using as a test account. Leave Callback URL blank.
Screen Shot 2016-02-26 at 11.07.23

Screen Shot 2016-02-26 at 10.26.18

If it all goes well, you’ll see this page. If it doesn’t work and says something about a phone number go back to Step 3. Or fix any other errors it throws up.
Screen Shot 2016-02-26 at 10.26.49

Next click on Keys and Access Tokens. Copy the API Key and the API Secret to a text file. These let anyone with access to them the ability to post from your account. So keep them secret if you haven’t made a test account and be careful if you are putting your code on Github later or sharing it publicly. Scroll down a click “Create my access token”.
Screen Shot 2016-02-26 at 10.27.53

Then add Access Token and the Access Token Secret to your text file too.
Screen Shot 2016-02-26 at 10.28.07

Your text file should be arranged like this, name it secret.txt and save it in the same place as your sketch for this example.
Screen Shot 2016-02-26 at 13.30.38

Processing Sketch Code

In our setup, we have to first import all out libraries. And then we have to read in the keys from our text file. And finally setup a twitter object.

Our draw method is what handles reading from the serial port. We’ll be reading in String data every loop of the draw method until we see TWEET or SEARCH. These are keywords we will use in our Arduino code later.

Our drawTweets() method is what handles drawing 1 tweet to the screen with each press of the button.

Our tweet method tweets the current time. If you adapt this code make sure to keep something unique about each tweet as twitter does not allow you to tweet the same status repeatedly. So here the time acts as our unique difference between each status.

This method gets the new tweets using a searchString based query and adds it to an array of status objects.

Arduino Wiring & Code

For the Arduino section of this tutorial you’ll need:

  • An Arduino board such as an Arduino Uno, or a cheap clone.
  • A breadboard.
  • Two pushbuttons.
  • Two resistors at around 220Ω.
Screen Shot 2016-03-25 at 11.40.52

To wire it up put each button across the middle of the breadboard. These are usually quite hard to sit in the breadboard holes so I reccomend flattening them with some needle nose pliers first. Then connect the upper right pin of the buttons are digital input pins, 4 & 2. The lower right pin of each buttons connects to the resistors which are then connected to the ground rail. The lower left pins are connected to the 5v rail. Our resistors are required to pull the input to ground, otherwise we will have a floating input and the buttons won’t work properly.

Our Arduino code is actually quite simple. The main problem with using pushbuttons and talking to processing is debouncing. Debouncing is when a button generates too many open/close transitions when pressed, due to mechanical and physical features of the button itself, and these transitions may be read into our code as multiple input attempts by the user. To solve this, we simply check twice in a short period of time to make sure the pushbutton is definitely pressed down. Without doing this, pressing the button once may cause unpredictable results. I’ve used the millis() function to keep track of the time passed since the button was pressed.

The other interesting part is that when one of the buttons is pressed, we will print "TWEET\n" to the serial console. And when the other button is pressed we will print "SEARCH\n" to the serial console. These strings are then picked up by our serial read in processing and dealt with accordingly.

Conclusion

This example only scratches the surface of what we can achieve using Twitter, Processing and Arduino. I would recommend reading through the Twitter4j example and really exploring what else you can achieve. In the future I will be adding examples of taking data from other web services such as Instagram and Facebook or weather data and showing you how you can quickly grab and use data with Arduino and Processing.

Leave a comment and tell me how you got on.

  • John Cantlin

    This was a very interesting project. Thanks for posting! The instructions were clear and easy to follow, particularly the surprisingly (to me) complicated task of setting up the Twitter App.

    As a novice Processing user, I had the most trouble getting the Processing code to work. A few of my problems and fixes may help another novice.

    (1) the posted code uses > and < and >= and <=. I had to replace these (in the Arduino code too) with >, =, and <= respectively.

    (2) my computer was only using COM5 so the serial list command, which I thought should get a "5" put in brackets [5}, is really looking for the first element of the serial port list and since the COM5 port is my only port, a zero, i.e. Serial.list()[0] is needed to read the first element in the returned serial port list. Your list may be different but it is the position in the returned list, NOT the port number, which goes in the Serial.list()[0] brackets.

    Both of my Arduino Uno buttons work, the one that sends out the Tweet with the current time seems easy enough to understand. But the sequence of events in the Processing code when I press the second button (the "search" button) is quite unclear to me. The current code has the line "String searchString = "#glenshee";" and it returns the search result in the Processing serial monitor – but if I change this seach string, even to a string with 8 characters, I get an "array of of bounds" error. So if anyone could explain a bit about what the code is supposed to do and how it is doing it when the "search" pushbutton is pressed I would appreciate it.

    Thanks for sharing this great project. Much appreciated.

  • Benjamin Gorman

    Hey John,

    Thanks for your thoughts! Issue 1) will be down to how HTML has formatted the characters when you pasted the code from a browser into a text editor. Annoying but it’s due to character encoding! 2) This is a good solution, I should have clarified how the serial list works, you are correct it’s essentially an array of all your ports!

    Now your question about the searchString is interesting. It’s because the code does no error checking if no tweets are found with that hashtag, for instance if I searched for #benjamingorman it’s unlikely I will get any tweets, so will get an index out of bounds response because there isn’t enough tweets to loop through, if you search for #worldcup you won’t have this issue! You could include some error checking on this and ensure that it only shows a random tweet from the number of tweets you found in the query!

    Cheers,

    Ben

  • John Cantlin

    Thank you for the prompt response and the useful insights into the program! I will do some experimenting based on your tips. I am planning to attempt to modify the program to Tweet the value of an analog sensor read by the Arduino. Ultimately I want to see if I can make it work (report the value of an analog sensor) using p5.js. Enjoy the rest of the weekend!

    Sincerely,

    John

  • kick_wunder

    hello! thank you for this awesome tutorial. I had a couple questions. My arduino code returns the errors:
    }
    ^
    exit status 1
    ‘gt’ was not declared in this scope

    and processing returns the error:
    expecting EOF, found List

    do you have any thoughts on these errors? Sorry I am new at this. Thank you!

  • kick_wunder

    Ok I reread what John had posted and realized I needed to fix ‘>’ and ‘<' symbols – sorry about that should have paid closer attention. So now the code seems to work… but it does not post to twitter. In the serial monitor it says "TWEET" and "SEARCH" but not sure why is doesn't appear on twitter. Anyway let me know if you have any suggestions. Thank you!!

  • Benjamin Gorman

    @kick_wunder:disqus Sounds like you might have not followed the Processing section correctly?