Introduction: PiMonkey: Create a Twitter Hashtag Monitoring Toy!
In this project we are going to create a Toy that reacts to a Hashtag on twitter. The toy monitors twitter, when it sees a certain hashtag used it turns on. I decided to use a monkey toy for this project, however any toy that has its own switch could be used! You could even use my code to turn on other electrical items, lights for example. The possibilities are endless.
I was disappointed with the lack of instructions online for the use of relays with Raspberry Pi, so I decided to create my own guide. We will be using Python code and a Raspberry Pi for the project, creating a nice small package. Do not be intimidated by this project as it is extremely easy to get started! and a great introduction to Python programming and the use of APIs.
I created this for a University Project about APIs. I am not vastly experienced using the Raspberry Pi with it's GPIO. So if i can do it so can you! The project is fairly simple once you get started.
An optional step is to customise the monkey of course. I decided to stitch the twitter logo onto his shirt.
If you find this instructable interesting please vote for it!
Credits:
Sparkfun: https://learn.sparkfun.com/tutorials/raspberry-pi...
Jeremy Foster: http://www.codefoster.com/tweetmonkey/
I also used the same method to create these Christmas lights that turn on when someone says #Christmas!
Step 1: Materials & Tools
Components
- Raspberry Pi (any model)
https://www.amazon.co.uk/Raspberry-Pi-Model-Quad-M...
I used a Raspberry Pi 2 Model B for this project, as I had it laying around, however a better option may be to purchase the Raspberry Pi 3, due to its integrated WiFi, therefore you will not have to purchase a USB wifi adaptor.
- 5v Micro USB Power Supply
https://www.amazon.co.uk/Raspberry-Pi-Power-adapte...
You can probably get away with using an old Micro-USB phone charger (I did). This would save on cost. Just make sure the phone charger using is rated at 5v 2A and it will work with the Pi!
- Micro SD Card
https://www.amazon.co.uk/Kingston-SDC4-8GBSP-Class...
You will also need a micro SD Card to install the operating system (software) for the Raspberry Pi. Again you probably already have one laying around! You may also need a USB SD card adaptor for your computer.
- Wifi Adapter
https://www.amazon.co.uk/Edimax-EW-7811Un-N150-Wir...
If you do not have a Raspberry Pi 3, then you will want to pick up a USB wifi adapter. The one I have linked above (Edimax EW-7811Un) is the one I used for this project, and is supported by the Raspberry Pi. If you already have one, or want to buy a different brand of adapter, then make sure it is compatible with Raspberry Pi by doing a quick google search.
- A case for your Pi (Optional)
https://www.amazon.co.uk/Raspberry-Pi-3-Black-case...
I like to use a case for all my Raspberry Pi projects, as it keeps the Raspberry Pi safe and secure. This is optional, as it is not required for the project to work, it just keeps everything self-contained and looking nice!
- Female to Female Jumper Wires
https://www.amazon.co.uk/Aukru-20cm-Female-Female-...
We will use Female to Female Jumper cables to connect our Relay to the Raspberry Pi's GPIO. We will not need a breadboard for this project. You will see that I used one, as I already had some Female to Male Jumper cables, I simply used a breadboard as a middle man between the relay and the Raspberry Pi. However you can just connect the relay straight to the Pi itself.
- A 5V 1 Channel Relay
https://www.amazon.co.uk/gp/product/B00ZR3B252/ref...
Don't be intimidated by this! A relay is simply a switch which is activated by a current or signal in one circuit (our Raspberry Pi) to open or close another circuit (Our Toy). You can look online to find a relay, the one above is the one I chose for this project. Most of the relays that are described as compatible with an Arduino should work with the Pi!
- Toy (& 2 x Double AA Batteries)
https://www.amazon.co.uk/Westminster-035594030300-...
This is the toy that we will bring to life when it monitors our chosen hashtag! You can use any toy that operates from batteries and has its own switch for this project, however I appreciate the comedic value of the monkey clapping its cymbals together. It was also a very good toy to use as the switch and battery compartment are at the bottom of the toy and easily acceptable. Please note we are not powering the monkey from the Raspberry Pi itself. We are just connecting our Relay (switch) in place of the original switch, the toy will still be powered from 2 AA batteries (you may need to purchase these separately).
- Single Core Wire
https://www.amazon.co.uk/Copper-Jumper-Single-Cond...
This single core wire will be used to connect our Toys circuit to the Relay. We can use solder for this, however if you cannot do this or do not have access to a soldering iron then electrical tape will be fine!
- USB Keyboard & Mouse
We will need a keyboard and mouse to connect to the Pi to do the initial set-up. You will probably have this already.
- A HDMI Cable & Monitor
To connect our Raspberry Pi to so that we can set it up & write the code.
Tools & Other Materials
- Drill (Optional); with the smallest drill bit you have.
- Wire cutters & strippers.
- Soldering Iron (Optional)
- Hot Glue Gun (Optional)
- Electrical Tape (If you do not wish to solder)
And that is it, all the materials and tools you will need to complete the project! As you can see the project is extremely affordable, as most of these objects you will have already. Raspberry Pi's are great for small projects like this as they are extremely affordable, especially if you pick up an older model from eBay. I would stick to at least using a Raspberry Pi 2 Model B, as I have not tested this project with older models.
Step 2: Installing Raspbian and Setting Up the Raspberry Pi.
https://www.andrewmunsell.com/blog/getting-started...
The above link is a great guide for installing the Raspbian Operating system onto the Raspberry Pi. I was using the latest version of Raspbian for this project (Jessie). I will write a brief description on how to set-up Raspbian, however there are a lot of comprehensive guides out there. I used windows to install Raspbian, although the above link describes how to set-up Raspbian on a Mac.
Windows
1)Download & Install Win32DiskImager.
https://sourceforge.net/projects/win32diskimager/
Download and install the above program, we will use this to install Raspbian onto our Micro SD Card.
2)Download the latest version of Raspbian (Operating System).
https://www.raspberrypi.org/downloads/raspbian/
Next you will need to download the .img file for Raspbian from the official website. I used 'Raspbian Jessie with Pixel' for this project. Extract the .zip file onto your desktop.
3) Insert the micro SD card into your computer.
Using a Micro SD to SD card adaptor you can insert the Micro SD card into your computer, you could also use a USB Micro SD or SD card adaptor for this.
4) Open 'Win32DiskImager', Select the downloaded .img file, Write to the micro SD card.
Open 'Win32DiskImager' and under 'Image File' browse and select the Raspbian '.img' you downloaded and extracted earlier. Make sure the drive letter of your Micro SD card is selected under 'Devices'. Click 'write', and wait for the progress bar to complete.
5) Insert the Micro SD into the Raspberry Pi.
You can now insert the Micro SD card into the Raspberry Pi. Connect your monitor to the Raspberry Pi via the HDMI cable, connect a USB keyboard & mouse and plug the Pi into the 5v Micro USB power supply. You should see you Pi boot up and go to the Desktop!
You can now continue to the next step!
Step 3: Relay Setup
Now its time to connect our relay and toy the the Raspberry Pi!
Firstly we'll plug in the relay. On the right side of your Pi you will see a set of pins. These our called the GPIO (General Purpose Input Output).If you are familiar with arduinos you will recognise these pins. We can connect a circuit to these pins and control the circuit in software.
It is very simple to plug the relay into the Raspberry Pi. I have created a circuit diagram for this project (see above). Firstly using a female to female jumper cable, connect the Raspberry Pi's 5V pin to the 'VCC' pin of the relay; it would be useful to use colour coded wires (Red for 5V, Black for ground & Yellow for data).
Next connect the Ground pin of the Raspberry Pi to the 'GND' pin of the relay.
Now locate Pin 22 on the Raspberry Pi (also known as GPIO 25). I will be referring to it as Pin 22, as this is the name the code I have written uses. I have attached a labelled diagram of the Pi's GPIO above in case you are unsure of which pin this is, you can also refer to my circuit diagram.
Now you have connected the relay to the Raspberry Pi!
Step 4: Modifying the Toy
We need to modify our toy in order to be able to connect it to the relay.
You can skip these steps if you do not wish to solder anything permanently. An easier step would be to simply use some electrical tape to stick two wires (with both ends stripped about 5mm) to the top of the two AA batteries. Run these wires out of the battery case once it is closed. Make sure to mark which wires running from the batteries are negative positive.
The neater method:
1) Drill a small hole in the corner of the battery door, use the smallest drill bit you have for this; this way you will not damage the original switch.
2) Solder one wire with both ends stripped (link provided to some suitable wire) to each of the metal contacts. You can use red and black wire to make the polarity easier to identify, however if not just label one of the wires. Run these wires through the hole you created in the previous step.
3) Although optional, it would be a good idea to use some hot glue to secure these wires in place. This will make it less difficult to pull the wires out (believe me I know). Close the battery door.
Now just touch the two wires together and your toy should start!
4) The final step is to connect the monkey to the relay. Use the image above as a guide. Unscrew the screw terminals, connect the positive wire to the right terminal of the relay and the negative wire to the centre terminal. If you have a different relay to mine, make sure you connect the positive wire to the 'Normally Closed' terminal. If you connect these wires wrongly you will have a toy that turns OFF when it senses a hashtag, and there is nothing more annoying than an always on clapping monkey!
The circuit is now complete, so in the next step we can move on to the python coding and setting up the Raspberry Pi!
Step 5: Generating Twitter API Keys & Tokens
This step sounds much harder than it actually is. I found a Youtube video walking you through the process step by step. Ignore the 'sociomole' references. I also created several screenshots of the process above. We need to generate some keys on twitter to use in our code that will enable us to access the Twitter API.
Read more about API's here:
http://techterms.com/definition/api
The Twitter API allows our code to access Twitter's data in order to monitor our chosen Hashtag. Our code will pull this data from the twittersphere, switch the relay and our monkey will then start clapping!
On your computer:
1) Go to this address: https://apps.twitter.com/ and sign in using your Twitter account. NOTE: Make sure you have a phone number assigned to your account.
2) On the 'Twitter Apps' page click the 'Create New App' button.
3) On the next page enter a Name & Description. The name and description can be anything you like, although the name has to be unique to you and not used before by someone else. Next enter a website URL, this could be a website you own, however as long as you start the address with 'http://' you could make up this address if you don't have your own website. Ignore the 'Callback URL' field, tick the box under 'Developer Agreement' and click 'Create your twitter application'.
4) On the next page click on the tab that says 'Keys & Access Tokens', scroll down to the bottom of this page and select 'Create my access tokens'.
5) It would be a good idea at this point to create a text document and save it on your desktop. Copy and paste the 'Consumer Key', 'Consumer Secret', 'Access Token' and the 'Access Token Secret' from this page into the text document. We will refer back to these keys in a later step.
Congratulations! You are now officially a developer.
Step 6: Editing the Code:
On your computer:
Download Notepad++: https://notepad-plus-plus.org/download/v7.2.2.html
We are going to be using this program to edit our code, and insert the keys that we generated in the last step. You can use any code/text editor, this is just the one that I prefer to use.
Here is the code I have written for this project:
import time<br>import RPi.GPIO as GPIO
from twython import TwythonStreamer
# Setup GPIO as output
GPIO.setmode(GPIO.BOARD)
GPIO.setup(22, GPIO.IN) # The pin number your relay is connected to (not the GPIO number).
# Enter the hashtag you want to monitor
TERMS = '#twittertoy'
# Twitter application authentication
APP_KEY = ''
APP_SECRET = ''
OAUTH_TOKEN = ''
OAUTH_TOKEN_SECRET = ''
class BlinkyStreamer(TwythonStreamer):
def on_success(self, data):
if 'text' in data:
print data['text'].encode('utf-8')
GPIO.setup(22, GPIO.OUT) # turn relay ON
time.sleep(3) # Enter amount of time here that you want your toy to be on for (in seconds).
GPIO.setup(22, GPIO.IN) # turn relay OFF
try:
stream = BlinkyStreamer(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
stream.statuses.filter(track=TERMS)
except KeyboardInterrupt:
GPIO.cleanup()
The code for this project is written in the Python programming language. The Raspberry Pi already comes with Python, so we do not need to install it.
1) Download the '.py' file I have already created for you called 'twittertoy.py' the download link will be at the bottom of this step. To make this easier for us later, create a folder named 'twittertoy' on you desktop, move the 'twittertoy.py' file into this folder. Open 'twittertoy.py' in Notepad++, or your text editor of choice.
2) If you did not use Pin 22 (GPIO Pin 25) of your Raspberry Pi to connect to the relay, then change all references to '22' in the code to the PIN NUMBER you chose (NOT the GPIO number). You will see this next to 'GPIO.setup'. If not then skip this step.
3) We need to insert the keys we generated in the last step into our code. Next to "APP_KEY =" copy and paste the 'Consumer Key' you generated, make sure the key is surrounded by single quotation marks with no spaces: APP_KEY = 'YOUR KEY'. Then next add your 'Consumer Secret' next to "APP_SECRET =", your 'Access Token' next to "OAUTH_TOKEN =" and your 'Access Token Secret' next to "OAUTH_TOKEN_SECRET =". Again make sure all of your keys are surrounded by single quotation marks.
4) Change the text next to 'TERMS =' to a # of your choice. You can also add your twitter handle, so that the toy will notify you when someone mentions you on twitter! Now save the file.
You are now done editing the code! I have commented sections in the code so that you can understand what they mean. The code basically tells the Raspberry Pi, if '#twittertoy' is found on twitter then turn the relay on for 3 seconds. If you want to change the amount of time that the relay is on for, then change the number next to "time.sleep(SECONDS HERE)".
In the next step we will be moving the code to the Raspberry Pi.
Attachments
Step 7: Configuring the Raspberry Pi
Now that you have installed Raspbian, and completed all of the above steps. Power up the Raspberry Pi again using, the 5V Micro USB power adapter, you should boot up onto the Desktop. Make sure you have connected your USB mouse and keyboard. Refer to the images above as a guide.
1) Configure your WiFi settings.
The first step is to set our WiFi settings (Plug your wifi adaptor in, if you need one). Select the WiFi settings in the top left hand corner of the screen, on the tool bar, choose your SSID and enter your WiFi password.
2) Transfer files.
On your computer, copy the 'twittertoy' folder we created earlier and paste it onto a USB thumb drive. Then insert the USB drive into the Raspberry Pi, and copy the 'twittertoy' folder to the '/home/pi/' directory of the Raspberry Pi. There is an icon on the toolbar to open the file explorer. There should be a pop-up when you plug in your USB, select open in file explorer to view the files on your USB drive.
3) Open the terminal.
When the you have transferred the 'twittertoy' folder into the /home/pi directory. Open a terminal window. and type:
sudo pip install twython --upgrade
And press enter.
This command will update the 'twython' package. Twython is a package for Python (the programming language used for the code), it allows us to connect to the Twitter API, and access the information we need in order to monitor our chosen hashtag. This step is neccecary, the latest Raspbian image comes with twython, however it seems to be an outdated version, and does not work with the code we wrote earlier.
Next type:
cd /home/pi/twittertoy
Press enter and then type:
sudo python twittertoy.py
This code will launch our Python script. Your toy should now turn on any time your chosen hashtag is used on twitter! If your hashtag was something more common, you should already see the tweets roll in on the command line. If you set a more obscure hashtag, enter it on twitter and see if your toy turns on. NOTE: you can stop the code by using CTRL-C.
Thats it! You have finished this instructable. If you want to be able to run the Raspberry Pi without a monitor, keyboard and mouse, then carry onto the final step.
Step 8: Run the Script on Boot
We want to be able to run the script without the use of a monitor, mouse or keyboard. To set-up the Raspberry Pi to run in headless mode and automatically run our Python script, follow the steps below:
1) Open the Raspberry Pi Configuration menu by clicking the on the raspberry logo in the top left corner of the screen. Select Preferences > Raspberry Pi Configuration. You should now see a menu that looks the same as the first image above. Next to 'Boot' select 'CLI'. Now select 'Wait for network', we need to select this as the Python Script needs an internet connection to connect to Twitter.
2) Open a new terminal window and type 'sudo nano /etc/profile'. Now use the arrow key to scroll to the bottom of this file. Underneath all of the other parameters write "sudo python /home/twittertoy/twittertoy.py". Now press CTRL-X, y for yes and then enter to save.
We just edited the file that lists the operations for the Raspberry Pi during boot, adding the command for starting the python script at the end of this list, starts our script during the boot sequence, meaning we now don't need to connect a monitor and keyboard.
Here is a video highlighting the process:
If you wanted to you could also start the script using SSH. I will not go into detail on using SSH in this guide however here is a great guide on setting it up:
Congratulations, you now have a Twitter Monitoring Toy!