Introduction: SimpleTweet_01 Python

Picture of SimpleTweet_01 Python

Arduino Python Twitter (Windows)

In this instructable we'll modify my simpleTweet_00 and rewrite the Processing code with Python. You can expect an ignorant walkthrough by an illiterate noob, but maybe that's just what you're looking for.

Before you begin:
If you need help installing Python, navigating Windows from the Command Prompt, or installing packages, then take a look at my instructable How to install Python packages on Windows 7 . It's a quick and dirty walkthrough but it should get you going asap.

And because simpleTweet_00 already explains the concept, I'll be brief:  Arduino sends a message via Serial to Python; Python sends a tweet. The idea here is to create a simple Arduino Python Twitter communication. For beginners.

Let's do it.

Step 1: Concept

Picture of 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(). The Python sketch picks up the Serial() 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.

Python uses python-twitter and OAuth to post the new state to your Twitter account. Done and done.

Step 2: Arduino

Picture of Arduino

This Arduino script differs from the original simpleTweet_00 Arduino script  in the use of Serial. Originally, we used Serial.write();  but that didn't seem to work so well here. I decided I wanted to send human-readable information through Serial, so I had to change the Arduino code from Serial.write() to Serial.println(), and not just that, but, to make a long story short, it seems to work best when inside the if() statement, like this: 
if (Serial.available()<=0) Serial.println("Closed door");


// **************************************************************************************************
// for use with simpleTweet_01_python.py

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);
}
// **************************************************************************************************

Step 3: Python

Picture of Python

If you don't know How to install Python Packages on Windows 7 then you *really * need to follow that link. It's my instructable. It's a set of directions, not explanations. You'll need to do that before you can use this code here. 

You've got Python installed (w/ help from the link above) and now you need to get your packages in order.
Python - get the Python 2.7.2 Windows Installer from http://www.python.org/download/  
pySerial http://pyserial.sourceforge.net/
simplejson http://pypi.python.org/pypi/simplejson
httplib2 - http://code.google.com/p/httplib2/
python-oauth2https://github.com/simplegeo/python-oauth2
python-twitterhttp://code.google.com/p/python-twitter/

Refer to my How to install Python Packages on Windows 7 instructable if you need help installing these.

To run a python script, open it in IDLE and hit "Run > Run Module".
To learn about YOUR TWITTER KEY, goto the next step.

#######################################################################################
# simpleTweet_01_python.py
# visit my instructables for more information
# https://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()

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

Step 4: Twitter

Picture of Twitter

* Create a Twitter account twitter.com  
* Register an application with Twitter https://dev.twitter.com/apps/new  

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 Python script simpleTweet_01_python you will enter this information in here:
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')


That's it. Not hard at all. 

Step 5: Circuit Board

Picture of 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...

Picture of In Conclusion...

The idea here was to take a simple Arduino Processing program and redo it for Arduino Python. You can use this Python script as a starting point for your own projects.
 
Good Luck!

Comments

LivelloAcqua (author)2017-07-05

https://dev.twitter.com/apps/new this page doesn't exist anymore!

russ_hensel (author)2016-01-23

I love the combination of Python and the Arduino. So I have created a collection about it. I have added your instructable, you can see the collection at: >> https://www.instructables.com/id/Arduino-and-Pytho...

Loveproblemsoluton (author)2015-02-17

Extraordinary Work.

lovemarrigespecalist (author)2015-02-14

excellent work.

Fabulous work.

Loveguruinindia (author)2015-02-08

Superb work

Muslimastrologerinindia (author)2015-02-08

good one.

VedicAstrology (author)2015-02-08

great spot

witchcraftSpel (author)2015-02-06

great work

VashikaranSpecialstBaba (author)2015-02-06

good one.

superb

MuskanSingh (author)2015-01-31

cool work.

Lovevashikaran (author)2015-01-31

nice

Lovemarriagespells (author)2015-01-31

Superb one.

BlackmagicSpt (author)2015-01-30

really nice

LoveMarriage (author)2015-01-30

superb work.

Vashikaranmantrafor (author)2015-01-30

Extra ordinary Work.

WitchCraftSpell (author)2015-01-29

good one.

SunilKmar (author)2015-01-28

nice work.

varunkmar (author)2015-01-28

good work.

Yuvrajsingh (author)2015-01-28

Great one.

Rahulkmar (author)2015-01-28

Superb.

irfanhaider (author)2015-01-28

very nice work.

elizazet (author)2015-01-21

i am your big fan

HypnotismSpecialst (author)2015-01-02

nice work

BabaVashikaranSpecialst (author)2015-01-02

nice chip set.

MarriageLoveSpecialst (author)2015-01-02

nice python. i like it.

Nice working.

Vashikaran (author)2015-01-02

nice work.

VashikarnMantra (author)2014-12-31

good one.

world famous astrologer (author)2014-12-30

Very nice.

 lovemarriagespell (author)2014-12-30

superb work like this.

WazifaforloveMarriage (author)2014-12-29

nice one.

Islamicvoodoospell (author)2014-12-29

beautiful work.

great work..

great spot

Nice Work Great Job sir.

Fundermax cladding (author)2014-12-09

This is awesome

vashikaran Baba (author)2014-12-04

nice one..

VashikaranforLove (author)2014-12-04

Awesome work..

vashikaranmantrainhindi (author)2014-11-18

i love with your job

vashikaranexpert (author)2014-11-18

Awesome like this..

loveproblemsolution (author)2014-11-15

good one..

johnsonpaul (author)2014-10-19

i am your big fan

GrahamAbbey (author)2014-09-25

such a use full pic

Rejanblink (author)2014-08-12

simple but very usefulll .. thankyou so much for sharing

Cringojames (author)2014-08-05

Hmm twitter needs you

Davementor (author)2014-08-05

great for newbies

StevenMccan (author)2014-08-01

great stuff

About This Instructable

17,866views

79favorites

License:

More by pdxnat:Twitter Mention Mood LightsimpleTweet_01 pythonHow to install Python packages on Windows 7
Add instructable to: