Instructables
Picture of Twitter Mention Mood Light
Twitter Mention Mood Light -- a mood light that alerts you when @username is mentioned on Twitter.

This is a simple intro in how to control your Arduino from Twitter. If you are new to Arduino Twitter / Arduino Processing Twitter / Arduino Python Twitter / Twitter Mood Light, then please refer to simpleTweet_00_processing  and simpleTweet_01_python (and How to install Python packages on Windows 7 ) for a crash course.


 
 
Remove these adsRemove these ads by Signing Up

Step 1: Concept: Arduino {Processing / Python} Twitter

Picture of Concept: Arduino {Processing / Python} Twitter
The Arduino Twitter mood light has been around for a few years. I made one in early 2010 and recently decided to update it for Twitter OAuth protocol (step 5.) This instructable has both the [ Arduino Processing Twitter ] and [ Arduino Python Twitter ] versions.

The general idea: You've got a LED generating a peaceful glow, cycling through a bunch of colors, and meanwhile you've got Processing or Python listening to Twitter for any mention of @yourUsername. When it finds a Twitter status with @yourUsername it writes to Arduino over Serial and Arduino changes the LED from peaceful glow to alert.

The circuit board (step 6) has two buttons: Reset and Send. The reset button changes the LED from "alert" back to "peaceful glow." The send button sends a Twitter status update to your Processing or Python layer, and from there on up to Twitter. When pressing the SEND button, hold it down until you see the flash of WHITE LIGHT (approx 1 second.)  This confirms the button push has been read by Arduino.

There is some confusion about Twitter Rate Limits . The Rate Limit is the number of times Twitter will let you hit it's servers per hour, currently 350 hits per hour. Go over that number and Twitter will block you. I made the same provision for this in both Processing and Python: wait 15 seconds between hits. In Processing, in void draw() , see delay(15000); . In the Python, in the while clause, see time.sleep(15).  This does not affect the timing of any button pushing or Serial calls.

The Arduino code is the same for both Processing and Python except when Arduino listens to Serial. Both Processing and Python pass an integer value of 1 (arduino.write(1) ) but Arduino receives a different value (numeric / ascii) from each, which is why you'll see these two lines in the Arduino code:

    if (serialMsg == 1) state = "mention"; // processing
    if (serialMsg == 49) state = "mention"; // python


This is because I'm not sure how to pass a string value of "mention " over Serial in Python. It's not critical, so I'll leave working as above, but if anyone has a solution for sending a string (arduino.write("mention") ), particularly in Python, please post in the comments below. 

The center of this project is the getMentions() function. It's interesting to compare how they look in Processing and in Python.

// Processing (java)
// search for any mention of @yourUsername
void getMention() {
  List mentions = null;
  try {
    mentions = twitter.getMentions();
  }
  catch(TwitterException e) {
    println("Exception: " + e + "; statusCode: " + e.getStatusCode());
}
  Status status = (Status)mentions.get(0);
  String newID = str(status.getId());
  if (oldID.equals(newID) == false){
    oldID = newID;
    println(status.getText()+", by @"+status.getUser().getScreenName());
   arduino.write(1); // arduino gets 1
  }
}

# Python
# search for any mention of @yourUsername
def getMention():
    status = api.GetReplies()
    newID = str(status[0].id)
    global oldID
    if (newID != oldID):
        oldID = newID
        print status[0].text+", by @"+status[0].user.screen_name
        arduino.write(1) # arduino gets 49

In both cases the id value received is in "long" format. By converting from "long" to "string" with str() we're able to compare the value and act on it. I had trouble doing that in long format. 
NicolasM15 days ago

thanks for your great work man, but i tried your code and it only prints out the tweets that I make. If a friend mentions me in their tweet I don't see a thing.

etoms9 months ago

Any guidance with the GET request delay?

Per Twitter's Dev site:

Rate limits in version 1.1 of the API are divided into 15 minute intervals, which is a change from the 60 minute blocks in version 1.0. Additionally, all 1.1 endpoints require authentication, so no longer will there be a concept of unauthenticated calls and rate limits.

While in version one of the API, an OAuth-enabled application could initiate 350 GET-based requests per hour per access token, API v1.1's rate limiting model allows for a wider ranger of requests through per-method request limits. There are two initial buckets available for GET requests: 15 calls every 15 minutes, and 180 calls every 15 minutes. Those primary buckets are outlined in detail here.

I keep going over the rate limit :(

micropuller2 years ago
I would really like to get this project to work, but up until now I haven't had any luck.

At first I tried downloading the library and putting it in the Processing sketchbook. After some trial and error I found out I had to put it in My Documents/Processing/Libraries/Twitter4j/Library.

When I tried to start the Processing sketch, I got the message: "the package "twitter4j" does not exist.
I tried putting the .jar files that were in the "lib" folder in the "Library" folder, but that generated the same message.

I then tried to download the "twitter4j.jar" file that can be found in the instructible (downloaded the file and renamed it to twitter4j.jar)
After I put that in the "Library" file and tried to run the sketch, a small window opened and I got the message: "NullPointerExeption". In the code "Status status = (status)mentions.get(0) was highlited.

I have some experience programming arduino's, but little to no experience with Processing. Could someone please point me in the right direction?
Download the twitter4j.jar and just drag the file onto the processing sketch window.
Hustleer2 years ago
Traceback (most recent call last):
File "/Users/mcasanas/Desktop/FG1LI7VGOW49P6U.py", line 51, in
getMention()
File "/Users/mcasanas/Desktop/FG1LI7VGOW49P6U.py", line 35, in getMention
status = api.GetReplies()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/twitter.py", line 2885, in GetReplies
return [Status.NewFromJsonDict(x) for x in data]
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/twitter.py", line 620, in NewFromJsonDict
return Status(created_at=data.get('created_at', None),
AttributeError: 'unicode' object has no attribute 'get'

Im getting this comment. please help :(
XZ3R02 years ago
Wonder if you could help me out. I got your code working nicely. So i thank you for making this tutorial as i didnt know where to start with the twitter api. Unfortunaly the API its still rather confusing for me so i can't really debug this myself. RIght when i start the "server" i guess you might call it. It pulls a tweet and sets off my arduino, i reset my arduino and its all fine. Randomly later it'll go off for a REALLY old mention. Reset again. Then it will pull the first tweet. This will keep happening at random intervals. Have you had this issue? Or know of an easy fix? I think i might attempt to use the ID of the tweet and make sure that the new mention has a > id.
starwood2 years ago
Dear all,

When trying out the python script I get the following error:

Traceback (most recent call last):
File "C:\Users\RMB\Downloads\FG1LI7VGOW49P6U(1).py", line 51, in
getMention()
File "C:\Users\RMB\Downloads\FG1LI7VGOW49P6U(1).py", line 36, in getMention
newID = str(status[0].id)
IndexError: list index out of range

Could use some help. Thanks!

Cheers

RJ
broadleyutb2 years ago
Hello.
Great tutorial, finally got it working for both Arduino+python and arduino+processing :) I moved the rgb LED from 5v to GND and it just started working?

Only problems now is that I can't seem to find were to change your tweet from (default for mines is #peaceful glow)
And also some of the LED descriptive colors on arduino code aren't actually changing to that color.

E.g ; for alert my arduino should flash red, black (off) but insted flashes light blue, white?

Can you help me please
pdxnat (author)  broadleyutb2 years ago
Howdy. Good job getting this far! As for the default message, look in the Arduino code (Step 2) at "void buttonSend()", particularly at the Serial.print() command....

void buttonSend(){ // Twitter posts sent here
send_btn_val = digitalRead(sButton);
if (send_btn_val == HIGH){
Serial.print("#peacefulGlow");
delay(200);
sent();
}
}

As for the LED colors, I don't have a good answer but make sure the physical pins are the same as the pins listed in the code....

int ledAnalogOne[] = {3, 5, 6}; // PWM RGB LED pins
// Analog LED 3 = redPin, 5 = greenPin, 6 = bluePin

If your LED is configured differently, then just keep messing with the connection points on the LED, on the board, and in the code.

Good Luck!
eniacmutiny2 years ago
This tutorial looks fantastic. Any chance you'd be able to provide a list of the necessary parts? I'm new to this, and I wasn't sure I had all the parts by just looking at the photo. Thanks and great job!
pdxnat (author)  eniacmutiny2 years ago
LED -
PWM RGB LED. This LED has 4 pins. Pin 1 Green; Pin 2 Power; Pin 3 Blue; Pin 4 Red. There is no pin to ground.

Resistors -
3x 220ohm
2x 100ohm
2x 10kohm

Buttons -
2x the little guys https://www.adafruit.com/products/367

You can use an Arduino with a breadboard or you can solder a circuit board from scratch using 16 or 18 gauge wire, I don't remember which. The single LED can be replaced with multiple LEDs but that'd require some redesign on your behalf and modification to the code, which you *should* be able to do after going through it once.
03coupr2 years ago
Does Twitter4j work on Mac?
pdxnat (author)  03coupr2 years ago
Yes it does.
03coupr2 years ago
Thanks a lot man. I'll do research into the analog v digital, is there anything I should know about them. Things I might miss on the internet.

I also have a RGB Piranha Super Flux Super Flux LED - Common Anode, will this work for the LED.

Thanks a lot for the help, Appreciate it.

Thanks
pdxnat (author)  03coupr2 years ago
Have a look at the diagram here:
http://www.instructables.com/id/Twitter-Mention-Mood-Light/step6/Circuit-Board/

At the bottom of the diagram you'll see "Digital Pins -->" and the LED plugs in to pins 3, 5, 6, while the buttons plug into pins 10, 11. I think you should try sticking to the digital pins for this project. I don't remember but I think the LED won't work properly on the analog pins, or something,

I don't know about the Piranha LED you mention, but you should test it out. I had to test every configuration before I understood what to do with the specific LED I used.

The breadboards are great for testing testing testing, don't be shy, prototype it until you understand it, that's really the best way to learn. You know, besides asking questions.

Good Luck!!
03coupr2 years ago
Thank you. Sorry for all the questions. When I first asked about the breadboard, is there any tips on how I would change the layout of the circuit. I only have the small breadboard that comes with the Arduino uno ?

Many thanks
pdxnat (author)  03coupr2 years ago
Well first off you can totally do this. Small bb will work just as well as anything, you just have less room for clumsy fingers. :-) yes, if you put the pins in different holes than what the code says, then change the code to match reality. In fact I encourage you to mess with it and see what happens. You won't break anything. But there is the whole analog vs digital pin-hole business that will limit where you connect to your arduino.
03coupr2 years ago
Thank you for getting back to me. I was also wondering, I have an ethernet board as well. Do I use that with this tutorial ?

Many Thanks
pdxnat (author)  03coupr2 years ago
I did not use an Ethernet board w this tutorial. I used a regular Arduino plugged into laptop w usb cable. Not sure if Ethernet would require extra work, but the fundamental code above shouldn't change.
03coupr2 years ago
Can you use a simple Bread Board, or do you need a circuit board?

Many Thanks
pdxnat (author)  03coupr2 years ago
Yes, you can totally do this w/ a breadboard.
Good luck!
klaurens2 years ago
Love your work man! can you do it with 4 normal leds?
pdxnat (author)  klaurens2 years ago
Yes, you can do it w/ 4 normal leds. They have 2 prongs instead of 4. You might need different resistors between the LED & the microprocessor, might not. The wiring would be different, of course, but basically the same. The code to control it would be different, simpler probably. Test your buttons before soldering them in place, they don't always line up the way you think they will.

Check out the diagram...
http://www.instructables.com/id/Twitter-Mention-Mood-Light/step6/Circuit-Board/
For each Button / LED pair:
Microprocessor -> resistor -> buttton ->(line A) resistor -> ground.
Microprocessor -> resistor -> buttton ->(line B) LED -> resistor -> microprocessor.

If you put it together, four buttons & four LEDs, what would you do with it?

Thanks for the props.
klaurens pdxnat2 years ago
I want to create the mood light like you have but what color you tweet, is what color light, lights up. I am really new to all of this and only got my first Arduino yesterday. And I am a twitter fanatic, so wanted to do this, but do not have RGB LED's.
pdxnat (author)  klaurens2 years ago
Congrats on your first Arduino! You're going to have so much fun. The brilliant thing about making stuff from the ground up is that if you can dream it then you can make it.

FYI - you can get RGB LEDs for $2 ea here: http://bit.ly/upYpiY at Adafruit. That's a competitive price. This is the LED I used but I've got a funky cover on it that I found at a local electronic hobby shop.

Mood lights are a fun and pretty straight forward concept and a great start to integrating with twitter.

Do you prefer coding in "Processing" or "Python" or some other language? This mood light project includes the code for each. I was still learning Python so I thought it'd be fun to explore the differences. There are enough tutorials out there and all coding follows the same basic structure. I've also got SimpleTweet_00 (Processing) and SimpleTweet_01 (Python.)

Have fun!
pdxnat (author)  pdxnat2 years ago
oops, that 2nd line should include power...

Microprocessor -> resistor -> buttton ->(line B) >power< LED -> resistor -> microprocessor.