Skip to content

Instantly share code, notes, and snippets.

@jrmedd
Last active October 12, 2015 21:08
Show Gist options
  • Save jrmedd/4087649 to your computer and use it in GitHub Desktop.
Save jrmedd/4087649 to your computer and use it in GitHub Desktop.
# Tweeting Letterbox
# by James Medd
# November 2012 (original version)
# http://jamesmedd.co.uk/
#!/usr/bin/python
import picamera
import RPi.GPIO as GPIO
import sys
import time
from twython import Twython
#OAuth details go here
CONSUMER_KEY = ""
CONSUMER_SECRET = ""
ACCESS_TOKEN = ""
ACCESS_TOKEN_SECRET = ""
#initialise Camera
camera = picamera.PiCamera()
#set input GPIO pin
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN)
twit = Twython(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
#timestamp, capture, and tweet an image
def capture_tweet():
timestamp = time.strftime("%d%m%Y-%H%M%S")
camera.capture(timestamp + ".jpg") #save image to disk
image = open(timestamp + ".jpg", 'rb')
timestamp = "@Username " + timestamp
twit.update_status_with_media(status=timestamp, media=image)
print "Tweeted image at " + timestamp #make a record in the Python output
#try/except for tidy starting/stopping of script
try:
print "Tweeting Letterbox initialised. Exit using Ctrl + c."
#loop to check PIR state/trigger a tweet (exit using Ctrl+C)
while True:
ir_val = GPIO.input(11)
if not ir_val:
time.sleep(0.5) #wait before checking again if nothing detected
elif ir_val:
capture_tweet() #capture and tweet image if triggered
while ir_val:
ir_val = GPIO.input(11)
time.sleep(0.5) #wait for sensor to reset/movement to stop before checking again
else:
print "Error"
except KeyboardInterrupt:
print "\nExiting.",
sys.exit()
@jrmedd
Copy link
Author

jrmedd commented Dec 19, 2012

Updated this morning, after discovering that 'time.strftime()' provided a timestamp with the kind of padding I wanted out of the box, eliminating the need for my messy, 'datetime'-based function.

@anddav87
Copy link

Brilliant idea, hadn't thought of monitoring the post! Excellent to monitor when parcels I am waiting for are received!

Just wondered if you have any idea how I can resolve this issue though:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 221: ordinal not in range(128)

Any advice appreciated as Google has failed me on this one :)

@jrmedd
Copy link
Author

jrmedd commented May 24, 2013

@anddav87: I've not come across that issue before, and I'm not sure I can troubleshoot it for you. Sorry!

Updated again this morning in line with a version I'm hoping will appear in MagPi soon. Includes a tidier start/stop using try/except.

@jrmedd
Copy link
Author

jrmedd commented Jun 3, 2014

Added an update to use the Raspberry Pi Camera module instead of a webcam. Also updated Twython-related code in line with their documentation guidelines etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment