Introduction: 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

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

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

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

* 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

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 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

author
LivelloAcqua made it!(author)2017-07-05

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

author
russ_hensel made it!(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...

author
Loveproblemsoluton made it!(author)2015-02-17

Extraordinary Work.

author
lovemarrigespecalist made it!(author)2015-02-14

excellent work.

author
vashikaranmantraforhusband made it!(author)2015-02-14

Fabulous work.

author
Loveguruinindia made it!(author)2015-02-08

Superb work

author
Muslimastrologerinindia made it!(author)2015-02-08

good one.

author
VedicAstrology made it!(author)2015-02-08

great spot

author
witchcraftSpel made it!(author)2015-02-06

great work

author
VashikaranSpecialstBaba made it!(author)2015-02-06

good one.

author
Husbandwifeproblemsolution made it!(author)2015-02-05

superb

author
MuskanSingh made it!(author)2015-01-31

cool work.

author
Lovevashikaran made it!(author)2015-01-31

nice

author
Lovemarriagespells made it!(author)2015-01-31

Superb one.

author
BlackmagicSpt made it!(author)2015-01-30

really nice

author
LoveMarriage made it!(author)2015-01-30

superb work.

author
Vashikaranmantrafor made it!(author)2015-01-30

Extra ordinary Work.

author
WitchCraftSpell made it!(author)2015-01-29

good one.

author
SunilKmar made it!(author)2015-01-28

nice work.

author
varunkmar made it!(author)2015-01-28

good work.

author
Yuvrajsingh made it!(author)2015-01-28

Great one.

author
Rahulkmar made it!(author)2015-01-28

Superb.

author
irfanhaider made it!(author)2015-01-28

very nice work.

author
elizazet made it!(author)2015-01-21

i am your big fan

author
HypnotismSpecialst made it!(author)2015-01-02

nice work

author
BabaVashikaranSpecialst made it!(author)2015-01-02

nice chip set.

author
MarriageLoveSpecialst made it!(author)2015-01-02

nice python. i like it.

author
SolutionHusbandwifeproblem made it!(author)2015-01-02

Nice working.

author
Vashikaran made it!(author)2015-01-02

nice work.

author
VashikarnMantra made it!(author)2014-12-31

good one.

author
world+famous+astrologer made it!(author)2014-12-30

Very nice.

author
%C2%A0lovemarriagespell made it!(author)2014-12-30

superb work like this.

author
WazifaforloveMarriage made it!(author)2014-12-29

nice one.

author
Islamicvoodoospell made it!(author)2014-12-29

beautiful work.

author
fundermaxdealerdistributer made it!(author)2014-12-24

great work..

author
Husband+Wife+Problem+Solution made it!(author)2014-12-10

great spot

author
toughened+glass+in+India made it!(author)2014-12-09

Nice Work Great Job sir.

author
Fundermax+cladding made it!(author)2014-12-09

This is awesome

author
vashikaran+Baba made it!(author)2014-12-04

nice one..

author
VashikaranforLove made it!(author)2014-12-04

Awesome work..

author
vashikaranmantrainhindi made it!(author)2014-11-18

i love with your job

author
vashikaranexpert made it!(author)2014-11-18

Awesome like this..

author
loveproblemsolution made it!(author)2014-11-15

good one..

author
vashikaran+astrologer made it!(author)2014-11-15

Awesome:)

author
johnsonpaul made it!(author)2014-10-19

i am your big fan

author
GrahamAbbey made it!(author)2014-09-25

such a use full pic

author
Rejanblink made it!(author)2014-08-12

simple but very usefulll .. thankyou so much for sharing

author
Cringojames made it!(author)2014-08-05

Hmm twitter needs you

author
Davementor made it!(author)2014-08-05

great for newbies

author
StevenMccan made it!(author)2014-08-01

great stuff

About This Instructable

17,776views

79favorites

License:

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