Artificial Intelligence

Creating a Twitter ticker with a Raspberry Pi

The Raspberry Pi is great if you want a dedicated device for a task that you can turn on, get it to do its thing and leave it alone.


The Raspberry Pi is great if you want a dedicated device for a task that you can turn on, get it to do its thing and leave it alone. Recently, I wanted to set up a little LCD screen that would continuously print out the latest tweets from a particular account. With a few components and some Python libraries, it was easy to put together something that I could just plug in and leave running. Here's how you can did it too - if you just want the final code, get it here.

Step 1: Getting data from Twitter

The python-twitter library makes it easy to retrieve tweets. On your Pi, run pip3 install python-twitter (I'm using Python 3) in the terminal. Next, you need some Twitter API credentials. Log in at http://apps.twitter.com and create a new app. Inside this app, go to Keys and Access Tokens, and create your access token. Copy the consumer key, consumer secret, access token and access token secret. Now you can get some tweets as easily as this:

import twitter
api = twitter.Api(consumer_key='YOUR CONSUMER KEY',
                  consumer_secret='YOUR CONSUMER SECRER',
                  access_token_key='YOUR ACCESS TOKEN',
                  access_token_secret='YOUR ACCESS TOKEN SECRET',
                  tweet_mode='extended')
tweets = api.GetUserTimeline(screen_name='metaltoad')
 
for tweet in tweets:
	print tweet.full_text

Other properties like created_at and hashtags are available too, and you can easily search Twitter with tweets = api.GetSearch(term="raspberry pi"), or constrain the returned tweets by number, date or location.

Step 2: Preparing tweets for display on an LCD screen

I've seen projects similar to this that work fine, but could do a better job of formatting the output. Words get broken across lines, HTML entities (like &) are not decoded and Unicode characters (from smart quotes to emojis and accented letters) that the display doesn't support are replaced with empty space. So I wanted to convert each tweet into one or more screenfuls of nicely presented text. Additionally, I wanted to make it easy to use a screen of any size, rather than tying the code to a single size (common sizes are 8x1, 16x2 and 20x4). To clean up the text, I first use html.unescape on the tweet text. Next, I pass the text to the unidecode library (installed with pip3 install unidecode). This converts non-ASCII characters to similar ASCII characters where it can. Then I split the text into words and chop words that are wider than the screen width into multiple words - very long words (eg email addresses or URLs) can cause the text on the LCD to wrap around and overwrite the beginning.

With clean tweet text in place, the next step is to put line breaks in at appropriate places. To do this, I loop through the words maintaining a tally of word lengths (plus one for each space). Each time that adding the next word would go over the screen width, I take the words from the last break up to that point, join them with spaces, add this string to an array of lines, then repeat the process until all words have been processed into lines. At the end of this process, I have a list of lines for each tweet that I will display, each one looking something like this (for a 20 column screen):

['"If you\'ve never', 'talked about', 'security, you can', "bet it's not being", 'perceived as a top', 'priority"', '@joaquinlippinco', 'https://t.co/P4CKXD8', '4Fd']

The last entry '4Fd' is part of the URL that was chopped up due to being longer than 20 characters.

Step 3: Communicating with an LCD screen

With the RPLCD library, it's easy to interface your Raspberry Pi with an LCD screen. There are two ways to connect: with I2C or GPIO. I2C requires fewer wires and does not use up your GPIO pins, but does need a port expander in addition to the LCD - it's easy to buy an LCD with this already in place though. Refer to http://rplcd.readthedocs.io/en/stable/getting_started.htm to see how to connect your Raspberry Pi to the LCD, and run pip3 install RPLCD to install the library.

Step 3a: Using I2C

You'll need to know the type of port expander you have (look on the chip for PCF8574, MCP23008 or MCP23017) and its address. To find this, sudo apt-get install -y i2c-tools python-smbus && sudo i2cdetect -y 1. This will install the necessary packages to work with I2C, then print out a table showing the addresses of attached I2C devices. Mine was 0x27. Now you can connect to it with:

from RPLCD.i2c import CharLCD
lcd = CharLCD('PCF8574', 0x27)

replacing the port expander type and I2C address if necessary.

Step 3b: Using GPIO

Once you've wired up the LCD, all you need to do is:

import RPi.GPIO as GPIO
from RPLCD import CharLCD
lcd = CharLCD(cols=16, rows=2, pin_rs=36, pin_e=18, pins_data=[16, 11, 40, 15])

replacing the pin numbers and number of rows and columns on your screen if necessary. When your program is exiting, call GPIO.cleanup() to leave the pins ready for another program to use them.

Step 4: Outputting text to the LCD

Having prepared the text of the tweets and connected to the LCD earlier, this part is very simple. I wrote a helper function lcd_print that clears the screen, prints the message passed to it as a parameter, and waits for a couple of seconds before continuing. For each tweet, I loop through the tweet's contents, outputting enough lines to fill a page at a time: lcd_print('\r\n'.join(tweet[i:i+LINES])) where i is the page counter and LINES is the height of the display. I output a screen of stars between tweets to delineate them. Once all tweets have been output, I fetch new tweets and repeat the process of printing them. And that's it!

Step 5: Running the program automatically

You might find it helpful to be able to run your script automatically when your Raspberry Pi boots up. This means you don't have to log in to your device to start it, and after power failure it will automatically restart. To do this, edit /etc/rc.local - from the terminal, sudo nano /etc/rc.local. Add python3 /home/pi/PATH/TO/YOUR/FILE.py & before exit 0. Additionally, if you are going to install your device somewhere new where it may be a hassle to plug in to a screen, keyboard and mouse just to enter the wifi password, you can do this in advance by editing /etc/wpa_supplicant/wpa_supplicant.conf. Add some lines like the following to tell your Raspberry Pi how to connect to the internet:

network={
        ssid="NETWORK NAME HERE"
        psk="NETWORK PASSWORD HERE"
        key_mgmt=WPA-PSK
}

Wrapping up

This is a fairly bare bones project as it stands. Here is the complete source code, heavily commented; you just need to change the settings as needed and you are good to go. You could extend it in many ways, for example: searching for particular tweet content, beeping when a fresh tweet is found, printing extra tweet information like date and time or author, adding a button to retweet a particular tweet, or playing a sound when a keyword is detected. Have fun!

Similar posts

Get notified on new marketing insights

Be the first to know about new B2B SaaS Marketing insights to build or refine your marketing function with the tools and knowledge of today’s industry.