๐Ÿ“ฃ๐Ÿ“ช ๐Ÿšš Adafruit will not be shipping USPS orders Monday October 14, 2019 ๐Ÿ—“. Expedited USPS orders placed after 11am ET ๐Ÿ•š Friday October 11 will go out Tuesday October 15 ๐Ÿ“ฃ๐Ÿ“ช๐Ÿšš
0

Example: Arduino to Twitter
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

Example: Arduino to Twitter

by pdxNat on Thu Jun 16, 2011 1:34 am

Howdy, I've posted two instructables online to help folks connect their Arduino projects to Twitter via usb, no ethernet. My journey began in these forums and I hope that by posting here I'll help someone else get where they're going.

* simpleTweet_00 - Arduino Processing Twitter w/ twitter4j
* simpleTweet_01_python - Arduino Python Twitter w/ python-twitter

With simpleTweet you connect a switch to Arduino (any on/off two-state device will work) and whenever that switch changes state (on/off, high/low) the Arduino code triggers a Serial() statement (Serial.write() in Processing; Serial.println() in Python.) That statement is passed through the usb port to your computer where Processing or Python picks it up, evaluates it, compares it to the last tweet posted to your twitter account (by comparing the first word of both messages,) and either does nothing (if the first words match we assume it's a duplicate) or posts the new message to Twitter.

The links above include straight-forward info on Twitter's OAuth registration and How to install Python Packages on Windows 7.

The comparison code mentioned above can be used to accept commands from tweets, too, by parsing out the first word and then acting on it. But this is a simple example, so there be a lot of functionality I've intentionally omitted.

I set out to create a simple example of how to connect your Arduino to Twitter. I wrote simpleTweet_00 in Processing and then adapted it in simpleTweet_01 to Python, along with some introductory How-To information for the Python-noobs (like me!) Both projects do the same thing and differ only in as much as their language requires or allows.

It was a lot of fun learning Python in this limited aspect. You might find this a convenient introduction to the similarities and difference between these two languages.

Again, intended to be simple, to be used as the foundation for your tinkering. Start here and build on it.

This post is a Thank You to all the lurkers who've helped noobs o'er the years.

####################################################
simpleTweet_00 - Arduino Processing Twitter w/ twitter4j

simpleTweet_00 Arduino code
Code: Select all | TOGGLE FULL SIZE
// 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 <http://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); //
  }
}


simpleTweet_00 Processing code
Code: Select all | TOGGLE FULL SIZE
// 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 <http://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
}

####################################################

Just so we're clear, the code above and the code below this line are separate sets. They do the same thing, but the code above is an Arduino-Processing set and the code below is an Arduino-Python set.

####################################################
simpleTweet_01_python - Arduino Python Twitter w/ python-twitter

simpleTweet_01 Arduino code
Code: Select all | TOGGLE FULL SIZE
// for use with simpleTweet_01_python.py
// visit my instructables for more information
// http://www.instructables.com/member/pdxnat/

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 (previousDoorState != currentDoorState){
      if (Serial.available()<=0) Serial.println("Opened door");
    }
  }
  if (magReed_val == HIGH){ // closed
    currentDoorState = 2;
    if (previousDoorState != currentDoorState){
      if (Serial.available()<=0) Serial.println("Closed door");
    }
  }
  previousDoorState = currentDoorState;
  delay(300);
}


simpleTweet_01 Python code
Code: Select all | TOGGLE FULL SIZE
# simpleTweet_01_python.py
# visit my instructables for more information
# http://www.instructables.com/member/pdxnat/

print 'running... simpleTweet_01_python'

# import libraries
import twitter
import serial
import time

# connect to arduino via serial port
arduino = serial.Serial('COM4', 9600, timeout=1)

# establish OAuth id with twitter
api = twitter.Api(consumer_key='YOUR_CONSUMER_KEY',
                  consumer_secret='YOUR_CONSUMER_SECRET',
                  access_token_key='YOUR_ACCESS_TOKEN_KEY',
                  access_token_secret='YOUR_ACCESS_TOKEN_SECRET')

# listen to arduino
def listenToArduino():
    msg=arduino.readline()
    if msg > '':
        print 'arduino msg: '+msg.strip()
        compareMsg(msg.strip())

# avoid duplicate posts
def compareMsg(newMsg):
    # compare the first word from new and old
    status = api.GetUserTimeline('yourUsername')
    prevMsg = [s.text for s in status]
    pM = ""+prevMsg[0]+""
    pM = pM.split()
    nM = newMsg.split()
    print "prevMsg: "+pM[0]
    print "newMsg: "+nM[0]
    if pM[0] != nM[0]:
        print "bam"
        postMsg(newMsg)
       
# post new message to twitter
def postMsg(newMsg):
    localtime = time.asctime(time.localtime(time.time()))
    tweet = api.PostUpdate(newMsg+", "+localtime)
    print "tweeted: "+tweet.text

while 1:
    listenToArduino()

####################################################
Last edited by pdxNat on Thu Jun 16, 2011 11:28 am, edited 1 time in total.
pdxNat
 
Posts: 16
Joined: Wed Apr 28, 2010 8:34 am

Re: Example: Arduino to Twitter

by adafruit on Thu Jun 16, 2011 9:52 am

great job! dont forget to submit this to the Make It Tweet contest on instructables!

adafruit
 
Posts: 12151
Joined: Thu Apr 06, 2006 4:21 pm
Location: nyc

Re: Example: Arduino to Twitter

by pdxNat on Thu Jun 16, 2011 11:23 am

Thanks!
Done and done.
* simpleTweet_00 - Arduino Processing Twitter w/ twitter4j
* simpleTweet_01_python - Arduino Python Twitter w/ python-twitter
pdxNat
 
Posts: 16
Joined: Wed Apr 28, 2010 8:34 am

Re: Example: Arduino to Twitter

by thoughtfix on Mon Jun 20, 2011 6:05 pm

I'm using the Twitter library on the Arduino playground for now, but it requires an Ethernet shield whereas this one bridges through a PC. I think I have a good idea based on your work here, though. Thanks for sharing!
---Daniel Gentleman
Open source projects: http://thoughtfix.com

thoughtfix
 
Posts: 70
Joined: Mon May 23, 2011 3:44 pm

Re: Example: Arduino to Twitter

by pdxNat on Mon Jun 20, 2011 8:33 pm

I just added a Twitter Mention Mood Light on instructables, with both Processing and Python code included. It's a mood light that also listens to Twitter for any mention of @yourUsername. Again, no Ethernet shield.
Cheers
pdxNat
 
Posts: 16
Joined: Wed Apr 28, 2010 8:34 am

Please be positive and constructive with your questions and comments.