Reputation: 1
I am trying a program like this:
When push to button, program automatically sends tweet. This program doesn't give error but always say "Not Pushed Button".
I am really a beginner in python. Anybody can help me please?
#!/usr/bin/env python
import sys
from twython import Twython
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.IN)
apiKey = 'xxxxxxxxx'
apiSecret = 'xxxxxxxxx'
accessToken = 'xxxxxxxxxx'
accessTokenSecret = 'xxxxxxxxx'
api = Twython(apiKey,apiSecret,accessToken,accessTokenSecret)
GPIO.add_event_detect(7, GPIO.FALLING)
tweetStr = "@raspberrytest34 deneme 1-2-3"
if GPIO.event_detected(7):
api.update_status(status=tweetStr)
print "Tweeted: " + tweetStr
else:
print "Not Pushed Button"
Upvotes: 0
Views: 49
Reputation: 31
Your program doesn't wait for anything. It just runs through, tests if the button has been pressed in the few milliseconds it took to initialize and then stops.
For testing you can add a simple
time.sleep(5)
to your code which will let the script wait for five seconds and then evaluate if you pressed the button in the meantime.
You could also do:
try:
while True:
if GPIO.event_detected(7):
api.update_status(status=tweetStr)
print "Tweeted: " + tweetStr
time.sleep(1)
except KeyboardInterrupt:
GPIO.cleanup()
print "\nBye"
This will run forever until you press Ctrl-C and respond to your keypresses once each second.
However the better way to handle this would be to hand a callback function to the keyboard interrupt. Watch out that the callback function can only communicate with the main script via global variables (please someone correct me if there's a better way!).
import time
api = Twython(apiKey,apiSecret,accessToken,accessTokenSecret)
tweetStr = "@raspberrytest34 deneme 1-2-3"
def send_tweet(channel):
global tweetStr
global api
api.update_status(status=tweetStr)
print "Tweeted: " + tweetStr
GPIO.add_event_detect(7, GPIO.FALLING, callback=send_tweet)
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
GPIO.cleanup()
print "\nBye"
Upvotes: 2