Skip to content

Instantly share code, notes, and snippets.

@amnuts
Last active December 29, 2015 15:19
Show Gist options
  • Save amnuts/7690052 to your computer and use it in GitHub Desktop.
Save amnuts/7690052 to your computer and use it in GitHub Desktop.
An example of making a motor spin (by ramping up and then down the speed) and sending a tweet when a button connected to the Raspberry Pi is pushed.
Uses libraries:
Useful sites:
Procedure:
  1. Install the Twitter and RPi.GPIO libraries
  2. Log in to https://dev.twitter.com/apps and create a new application
    1. Enter your application's name (has to be unique!), description and url (I set mine up on a specific port on my network) - don't need a callback url - and create the app
    2. Once added, go to the application's settings tab and select the 'access type' of 'Read and write' and save the settings
    3. In the details tab click on the 'create my access token' button
    4. You now have your consumer key and consumer secret key
import RPi.GPIO as GPIO
from time import sleep
import os
from twitter import *
from random import choice
from datetime import datetime
op1 = 11
op2 = 13
btn = 15
CONSUMER_KEY = 'xxxxxx'
CONSUMER_SECRET = 'xxxxxx'
oauth_filename = os.path.expanduser('~/.twitter_oauth')
doorbell_tweets = [line.strip() for line in open(os.path.expanduser('messages.txt'))]
GPIO.setmode(GPIO.BOARD)
GPIO.setup(op1, GPIO.OUT)
GPIO.setup(op2, GPIO.OUT)
GPIO.setup(btn, GPIO.IN)
motor = GPIO.PWM(op1, 100)
motor.start(0)
motor_pause = 0.02
button_pause = 0.05
# prevent 'bounce' results by buffering the input and sleeping ever so
# slightly before reading the input again
prev_input = 0
try:
while True:
input = GPIO.input(btn)
if ((not prev_input) and input):
print("Button pressed")
for i in range(0, 101):
motor.ChangeDutyCycle(i)
sleep(motor_pause)
sleep(3)
for i in range(100, -1, -1):
motor.ChangeDutyCycle(i)
sleep(motor_pause)
d = datetime.now()
msg = choice(doorbell_tweets).format(d)
if not os.path.exists(oauth_filename):
oauth_dance('APP_NAME', CONSUMER_KEY, CONSUMER_SECRET, oauth_filename)
oauth_token, oauth_secret = read_token_file(oauth_filename)
t = Twitter(auth=OAuth(oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET))
t.statuses.update(status=msg)
prev_input = input
sleep(button_pause)
except KeyboardInterrupt:
motor.stop() # stop the motor PWM output
GPIO.cleanup() # clean up GPIO on CTRL+C exit
There's somebody at the door!
It's now {0:%I}:{0:%M} of the {0:%p} and someone did ring the bell
Someone rang the door bell
My button, it hath don been pressed
I have been summoned on {0:%A}, {0:%d}. {0:%B} {0:%Y} {0:%I}:{0:%M}{0:%p}
Who is this tooting my bell?
Ring not, lest thee arouse me (from my slumber)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment