Introduction: SimpleTweet_00 Processing

Arduino Processing Twitter
Post a tweet when your sensor changes states, using Arduino, Processing, and twitter4j.
Note: I've got a Python version of this project here: https://www.instructables.com/id/simpleTweet01python/

In the video you'll see two lines appear. They look like this:
new tweet --:{ Opened door at 14:21:57}:--
new tweet --:{ Closed door at 14:22:1}:--

These confirm that new messages were sent to Twitter when the switch opened and closed.
Visit twitter.com/msg_box to see the timeline.

Step 1: Concept

The idea for this project was to develop generic code allowing you to automatically generate tweets based on input to your Arduino. This example uses a magnetic reed switch, which is your basic on / off switch. You can use this code as is for any two-state switch or modify it for more diversity.

We attach the magnetic reed sensor to my office door and door-frame. A wire runs from the magReed sensor to a pin in the Arduino circuit. Arduino watches that pin's status, HIGH or LOW, and when the status changes from one to the other Arduino reports on that change through Serial.write(). The Processing sketch picks up the Serial.write() call and checks to see if the current state is the same as the last one posted to Twitter. If the two states are the same then it will not post, but if the new state is different from the previous state, then we're in business.

Processing uses twitter4j and OAuth to post the new state to your Twitter account. Done and done.

Step 2: Arduino

// simpleTweet_00_a

/*
 simpleTweet_00 arduino sketch (for use with
 simpleTweet_00 processing sketch) by @msg_box june2011

 This script is intended for use with a magnetic reed switch,
but any on/off switch plugged into pin #10 will readily work.

The Arduino is connected to a circuit with a sensor that
triggers the code: Serial.write(n); where n = 1 or 2.
The Processing sketch listens for that message and then
uses the twitter4j library to connect to Twitter
via OAuth and post a tweet.

To learn more about arduino, processing, twitter4j,
OAuth, and registering your app with Twitter...
visit <https://www.instructables.com/id/Simple-Tweet-Arduino-Processing-Twitter/>
visit <http://www.twitter.com/msg_box>

This code was made possible and improved upon with
help from people across the internet. Thank You.
Special shoutouts to the helpful lurkers at twitter4j,
arduino, processing, and bloggers everywhere, and
to the adafruit & ladydada crowdsource.
And above all, to my lovely wife, without
whom, none of this would have been possible.

Don't be a dick.
*/

const int magReed_pin = 10; // pin number
int magReed_val = 0;
int currentDoorState = 1; // begin w/ circuit open
int previousDoorState = 1;

void setup(){
Serial.begin(9600);
pinMode(magReed_pin, INPUT);
}

void loop(){
watchTheDoor();
}

void watchTheDoor(){
magReed_val = digitalRead(magReed_pin);
if (magReed_val == LOW){ // open
currentDoorState = 1;
}
if (magReed_val == HIGH){ // closed
currentDoorState = 2;
}
compareStates(currentDoorState);
}

void compareStates(int i){
if (previousDoorState != i){
previousDoorState = i;
Serial.write(i);
delay(1000); //
}
}

Step 3: Processing

Install twitter4j

You'll need to install the twitter4j library so it can be used by Processing.
Get it here: http://twitter4j.org/en/index.html#download
Install it here (or equivalent): C:\Program Files\processing-1.5.1\modes\java\libraries
You're done.
Access it here: Processing > Sketch > Import Library... > twitter4j
And when you do, it'll add this to the top of your code:
import twitter4j.conf.*;
import twitter4j.internal.async.*;
import twitter4j.internal.org.json.*;
import twitter4j.internal.logging.*;
import twitter4j.http.*;
import twitter4j.api.*;
import twitter4j.util.*;
import twitter4j.internal.http.*;
import twitter4j.*;
Incidentally, you'll also add Serial I/O from the Sketch > Library, but that's not important right now.

So why do you need twitter4j? The short answer is that it provides you with simple functionality so you don't have to write a whole bunch of crazy code every time you want to access Twitter. We use twitter4j because it's awesome and it makes our job easier. 

// #####################################################################
// #####################################################################

// simpleTweet_00_p

/*
 simpleTweet_00 processing sketch (for use with
 simpleTweet_00 arduino sketch) by @msg_box june2011

 The Arduino is connected to a circuit with a sensor that
triggers the code: Serial.write(n); where n = 1 or 2.
The Processing sketch listens for that message and then
uses the twitter4j library to connect to Twitter
via OAuth and post a tweet.

compareMsg() is added in case you want to compare
the current and previous tweets to prevent retweets.

This Processing code requires the twitter4j library
and your registered app info from dev.twitter.com

To learn more about arduino, processing, twitter4j,
OAuth, and registering your app with Twitter...
visit <https://www.instructables.com/id/Simple-Tweet-Arduino-Processing-Twitter/>
visit <http://www.twitter.com/msg_box>

This code was made possible and improved upon with
help from people across the internet. Thank You.
Special shoutouts to the helpful lurkers at twitter4j,
arduino, processing, and bloggers everywhere, and
to the adafruit & ladydada crowdsource.
And above all, to my lovely wife, without
whom, none of this would have been possible.

Don't be a dick.
*/

import processing.serial.*;

import twitter4j.conf.*;
import twitter4j.internal.async.*;
import twitter4j.internal.org.json.*;
import twitter4j.internal.logging.*;
import twitter4j.http.*;
import twitter4j.api.*;
import twitter4j.util.*;
import twitter4j.internal.http.*;
import twitter4j.*;

static String OAuthConsumerKey = "YOUR CONSUMER KEY";
static String OAuthConsumerSecret = "YOUR CONSUMER SECRET";
static String AccessToken = "YOUR ACCESS TOKEN";
static String AccessTokenSecret = "YOUR ACCESS TOKEN SECRET";

Serial arduino;
Twitter twitter = new TwitterFactory().getInstance();

void setup() {
size(125, 125);
frameRate(10);
background(0);
println(Serial.list());
String arduinoPort = Serial.list()[0];
arduino = new Serial(this, arduinoPort, 9600);
loginTwitter();
}

void loginTwitter() {
twitter.setOAuthConsumer(OAuthConsumerKey, OAuthConsumerSecret);
AccessToken accessToken = loadAccessToken();
twitter.setOAuthAccessToken(accessToken);
}

private static AccessToken loadAccessToken() {
return new AccessToken(AccessToken, AccessTokenSecret);
}

void draw() {
background(0);
text("simpleTweet_00", 18, 45);
text("@msg_box", 30, 70);
listenToArduino();
}

void listenToArduino() {
String msgOut = "";
int arduinoMsg = 0;
if (arduino.available() >= 1) {
arduinoMsg = arduino.read();
if (arduinoMsg == 1) {
msgOut = "Opened door at "+hour()+":"+minute()+":"+second();
}
if (arduinoMsg == 2) {
msgOut = "Closed door at "+hour()+":"+minute()+":"+second();
}
compareMsg(msgOut); // this step is optional
// postMsg(msgOut);
}
}

void postMsg(String s) {
try {
Status status = twitter.updateStatus(s);
println("new tweet --:{ " + status.getText() + " }:--");
}
catch(TwitterException e) {
println("Status Error: " + e + "; statusCode: " + e.getStatusCode());
}
}

void compareMsg(String s) {
// compare new msg against latest tweet to avoid reTweets
java.util.List statuses = null;
String prevMsg = "";
String newMsg = s;
try {
statuses = twitter.getUserTimeline();
}
catch(TwitterException e) {
println("Timeline Error: " + e + "; statusCode: " + e.getStatusCode());
}
Status status = (Status)statuses.get(0);
prevMsg = status.getText();
String[] p = splitTokens(prevMsg);
String[] n = splitTokens(newMsg);
//println("("+p[0]+") -> "+n[0]); // debug
if (p[0].equals(n[0]) == false) {
postMsg(newMsg); 
}
//println(s); // debug
}

Step 4: Twitter

To post a tweet, do the following:

* Install twitter4j  http://twitter4j.org/en/index.html#download
* (Update: I've attached "twitter4j.jar" to this instructable page.)
* Create a Twitter account  twitter.com
* Register an application with Twitter   https://dev.twitter.com/apps/new

Install twitter4j

You'll need to install the twitter4j library so it can be used by Processing.
Get it here: http://twitter4j.org/en/index.html#download
Install it here (or equivalent): C:\Program Files\processing-1.5.1\modes\java\libraries
You're done.
Access it here: Processing > Sketch > Import Library... > twitter4j
And when you do, it'll add this to the top of your code:
import twitter4j.conf.*;
import twitter4j.internal.async.*;
import twitter4j.internal.org.json.*;
import twitter4j.internal.logging.*;
import twitter4j.http.*;
import twitter4j.api.*;
import twitter4j.util.*;
import twitter4j.internal.http.*;
import twitter4j.*;

Incidentally, you'll also add Serial I/O from the Sketch > Library, but that's not important right now.

So why do you need twitter4j? The short answer is that it provides you with simple functionality so you don't have to write a whole bunch of crazy code every time you want to access Twitter. We use twitter4j because it's awesome and it makes our job easier.

Create a Twitter account

You've probably already got one (or twelve) but for the absolute noob, take heart. It's easy.
Goto twitter.com and set up an account. Make it a public account, that way if you ever want your friends to look at it they don't have to go through a whole bunch of hooey to get there. And don't post personal stuff like "Out of town, leaving diamonds on back porch." 

You'll see people using the "@" and "#" symbols a lot. Put @ before a username and # before a concept. For example, if you post the following tweet "I enjoyed the @msg_box simpleTweet_00 on @instructables #goodtimes" then that tweet will get sent to my feed (and to instructables's feed too) and it'll get added to a cache of all posts that have ever used the phrase "#goodtimes." There's more, but it's not within the scope of this lesson. Play with it. You'll figure it out.

Register an application with Twitter

What does that even mean? Relax. Think of it this way:  you're creating a set of special high-tech usernames and passwords so the stuff you make can access Twitter. It's like Twitter is this big castle with a front door for all the human guests and a back door for all the automated service personnel. These high-tech usernames and passwords are called OAuth. OAuth lets your device access Twitter through the service entrance.

Having already created my Twitter account @msg_box I then went here https://dev.twitter.com/apps/new to get my OAuth password info. Review the three attached images of the forms .

First Page: Make sure you check "Client " and not "Browser", and that you allow "Read & Write ."
Second Page: Here's where you find your CONSUMER KEY and your CONSUMER SECRET
Third Page: Here's where you find your ACCESS TOKEN and your ACCESS TOKEN SECRET

You will need this information when your program logs into Twitter (via the service entrance.) In the Processing script simpleTweet_00_p you will enter this information in here:
static String OAuthConsumerKey = "YOUR CONSUMER KEY";
static String OAuthConsumerSecret = "YOUR CONSUMER SECRET";
static String AccessToken = "YOUR ACCESS TOKEN";
static String AccessTokenSecret = "YOUR ACCESS TOKEN SECRET";


That's it. Not hard at all.


Step 5: Circuit Board


Breadboard vs Circuit Board
The fasted way to hack this project together is with a breadboard (image). The breadboard, or solderless breadboard, is perfect for prototyping, for proving that your circuit works as you expect it to. That's because the breadboard allows you to attach and disconnect wires without any forethought or commitment or difficulty. With a breadboard, if your circuit does not perform the way you thought it would, then you can take it apart and reassemble it as many times as you like until you've got it right. After you've proven the concept and you know your circuit is right, then it's a good idea to solder together a real circuit board. I'm a big fan of soldering your own circuit boards. It's fun and easy and adds a special element of ownership to a project. If you want to reproduce lots of copies of your circuit, then you should consider printed circuits. Printed Circuits are the next step after Circuit Boards and are a great way to share your project with others, especially when it's a complicated circuit. You can order printed circuits or make them on your own. 

Step 6: In Conclusion....

The idea for this project was to develop generic code allowing you to automatically generate tweets based on input to your Arduino. With this code you now have the foundation for a tweeting empire. This project was simple and fun, but imho it's not a hack, it's a make. 

I did not bust anything open, like a door alarm and piggyback on it's systems. That'd be a hack. Instead I built a clean prototype, I made it. And I had fun. I'll look for something to hack and be back with more good fun. 

Cheers!

Adafruit Make It Tweet Challenge

Participated in the
Adafruit Make It Tweet Challenge