PiFace control and display

Lead Image © photoestelar, 123RF.com

Pretty Face

PiFace Control and Display makes it possible to build a variety of clever Raspberry Pi-based projects that require basic input and output. We help you to get started with this useful board.

To interact with a Raspberry Pi, you need a way to input commands and read the output. In most cases, this means using a keyboard and a monitor connected directly to the Raspberry Pi. Alternatively, you can use a remote machine with a monitor and a keyboard to access and control the Raspberry Pi via an SSH connection. Both approaches have their drawbacks, though. Having a monitor and keyboard connected to the Raspberry Pi precludes you from building autonomous and portable projects, whereas controlling a Raspberry Pi via SSH requires a network connection between two machines.

However, a third option is available to you, courtesy of PiFace Control and Display (PiFaceCAD for short) [1]. This board (Figure 1) features a 16x2 character display, a set of physical switches, a navigation switch, and an IR receiver – essentially everything you need for basic input and monitoring.

Figure 1: The PiFace Control and Display unit. (© 2013 OpenLX SP Ltd.)

Getting Started with PiFaceCAD

PiFaceCAD is available in two versions: the one compatible with the original Raspberry Pi models and PiFaceCAD 2 for Raspberry Pi 2 and Raspberry Pi B+. When ordering PiFaceCAD, make sure you're getting the right version for your Raspberry Pi model. Installing the board is a matter of plugging it into Raspberry Pi's GPIO port. To program PiFaceCAD, you need to install the pifacecad Python library and accompanying software, which can be done by running the following commands:

sudo apt-get update && sudo apt-get upgrade
sudo apt-get install python{,3}-pifacecad

With all the pieces in place, you are probably eager to give PiFaceCAD a try, and the supplied software makes that easy. The bundle includes several ready-made Python scripts that demonstrate PiFaceCAD's capabilities. The sysinfo.py script, for example, displays key system info, such as Raspberry Pi's IP address, RAM usage, and processor load. To run the script once, execute the command:

python3 /usr/share/doc/python3-pifacecad/examples/sysinfo.py

If everything works properly, the PiFace should light up and display the system info. If you want to run the script continuously, you can launch it as a service using the

sudo service pifacecadsysinfo start

command. (Use stop instead of start to terminate the service.) To run the script automatically on boot, execute the sudo update-rc.d pifacecadsysinfo defaults command.

Of course, playing with the prefabricated scripts is only part of the fun, and to use the board for your own projects, you need to master its basic programming techniques. To achieve that, you might want to start with something as simple as a Python script that displays the "Hello World!" message on PiFaceCAD's display for a specified period of time and then clears the screen, as shown in Listing 1.

Listing 1

helloworld.py

01 #!/usr/bin/python
02 import pifacecad, time
03 cad = pifacecad.PiFaceCAD()
04 cad.lcd.backlight_on()
05 cad.lcd.write('Hello World!')
06 time.sleep (5)
07 cad.lcd.backlight_off()
08 cad.lcd.cursor_off()
09 cad.lcd.blink_off()
10 cad.lcd.clear()

Save the script as helloworld.py, make it executable using the chmod +x helloworld.py command, and run the script by issuing the ./helloworld.py command.

Even if you are new to Python, you shouldn't have problems figuring out how the script works. The cad = pifacecad.PiFaceCAD() statement creates a PiFaceCAD object that can be manipulated through the supported functions. The cad.lcd.backlight_on() function turns the display's backlight on, and the cad.lcd.write('Hello World!') routine outputs the specified text on the screen. The latter function displays the text starting at the cursor's current position, which is initially in the top-left corner of the screen. However, you can control the position of the cursor using the cad.lcd.set_cursor() function that takes two arguments: the column and row. For example, the cad.lcd.set_cursor(3, 1) statement moves the cursor to the third column of the second row on the display.

Even this really simple script can be put to some practical uses. For example, using the Python Bottle framework, you can whip up a no-frills web app that allows anyone to push messages to PiFaceCAD via a browser (Listing 1). To do this, you need to install the Bottle framework on the Raspberry Pi first using the commands:

sudo apt-get update
sudo apt-get install python-pip
sudo pip install bottle

Then, paste the code shown in Listing 2 into a new text file and save it under the name piface-bottle.py. Make the script executable and launch it using the ./piface-bottle.py command. Point your browser to http://127.0.0.1:8080 (replace 127.0.0.1 with the actual IP address of the Raspberry Pi), enter a message, press Send, and you should see the text displayed on PiFaceCAD's screen.

Listing 2

Send a Message Python Script

01 #!/usr/bin/python
02 from bottle import post, route, request, run
03 import os, time, urllib, pifacecad
04 cad = pifacecad.PiFaceCAD()
05 @route('/')
06 @route('/', method='POST')
07 def receive_msg():
08     if (request.POST.get("send")):
09         cad.lcd.backlight_on()
10         msg = urllib.unquote_plus(request.forms.get('msg'))
11         cad.lcd.write(msg)
12         time.sleep (5)
13         cad.lcd.backlight_off()
14         cad.lcd.cursor_off()
15         cad.lcd.blink_off()
16         cad.lcd.clear()
17     return """
18     <title>PiFace Bottle</title>
19     <meta name="viewport" content="width=device-width, initial-scale=1">
20     <form method="POST" action="/">
21     <div id="content">
22     <p class="right">Message: <input name="msg" type="text" size="25"/></p>
23     <p><input id="btn" name="send" value="Send" type="submit" /></p>
24     </div>
25     """
26 run(host="0.0.0.0",port=8080, debug=True, reloader=True)

In addition to standard characters like letters and numbers, PiFaceCAD can also handle so-called custom bitmaps, or user-defined characters represented as a sequence of decimal or hex values. Designing custom bitmaps by manually specifying the correct value sequence can be a rather laborious process. Fortunately, the HD44780 LCD User-Defined Graphics page [2] provides a list of ready-made bitmaps along with their decimal and hex values. Better still, the page provides a simple tool for designing your own bitmaps.

Once your bitmap is ready, you need to add and save it on PiFaceCAD. PiFaceCAD can store up to eight custom bitmaps, and the pifacecad library provides all the necessary functions to define and save bitmaps. The code in Listing 3 defines an alarm bell bitmap, saves it to the PiFaceCAD memory and displays the bitmap on the screen.

Listing 3

Alarm Bell

01 #!/usr/bin/python
02 import pifacecad
03 cad = pifacecad.PiFaceCAD()
04 alarm_bell = pifacecad.LCDBitmap([0x4, 0xe, 0xe, 0xe, 0x1f, 0x0, 0x4])
05 cad.lcd.store_custom_bitmap(0, alarm_bell)
06 cad.lcd.write_custom_bitmap(0)

Bitmaps can be useful for more than just prettifying output. Using bitmap icons can also save a lot of valuable screen space, thus squeezing more info on PiFaceCAD's 16x2 LCD. The script in Listing 4, for example, uses bitmaps as markers for temperature in Celsius as well as sunrise and sunset times. This script also demonstrates how to fetch, process, and display data in the JSON format fetched from a web API. In this case, the script acquires weather data from the OpenWeatherMap service and extracts the temperature, sunrise, and sunset values. The script then generates three bitmaps for each value and displays the output on the LCD screen.

Listing 4

Show Weather Python Script

01 #!/usr/bin/python
02 import pifacecad
03 import os, json, urllib2, datetime
04 city = "Berlin"
05 country = "DE"
06 json_data = urllib2.urlopen("http://api.openweathermap.org/data/2.5/weather\
   ?q="+city+","+country+"&units=metric&cnt=7&lang=en")
07 data = json.load(json_data)
08 json_data.close()
09 sunrise = datetime.datetime.fromtimestamp(int(data['sys']['sunrise'])).\
   strftime("%H:%M")
10 sunset = datetime.datetime.fromtimestamp(int(data['sys']['sunset'])).\
   strftime("%H:%M")
11 temperature = "{0:.1f}".format(data['main']['temp'])
12 cad = pifacecad.PiFaceCAD()
13 celsius = pifacecad.LCDBitmap([0x18, 0x18, 0x3, 0x4, 0x4, 0x4, 0x3])
14 up_arr = pifacecad.LCDBitmap([0x0, 0x0, 0x4, 0xe, 0x1f, 0x0, 0x0])
15 down_arr = pifacecad.LCDBitmap([0x0, 0x0, 0x1f, 0xe, 0x4, 0x0, 0x0])
16 cad.lcd.store_custom_bitmap(0, celsius)
17 cad.lcd.store_custom_bitmap(1, up_arr)
18 cad.lcd.store_custom_bitmap(2, down_arr)
19 cad.lcd.backlight_on()
20 cad.lcd.write(temperature)
21 cad.lcd.write_custom_bitmap(0)
22 cad.lcd.write('\n')
23 cad.lcd.write_custom_bitmap(1)
24 cad.lcd.write(sunrise + ' ')
25 cad.lcd.write_custom_bitmap(2)
26 cad.lcd.write(sunset)

In addition to the LCD, PiFaceCAD features four regular switches and a navigation switch that let you interact with the Raspberry Pi. Additionally, the pifacecad library provides tools for working with the switches. At the most basic level, you would want to be able to read the status of a specific switch. One way to do this is to poll the desired switch at specific time intervals, and the simple script below does just that:

#!/usr/bin/python
import pifacecad, time
cad = pifacecad.PiFaceCAD()
while True:
    print cad.switches[0].value
    time.sleep(1)

This script runs an infinite loop that polls the first switch every second. If the switch is pressed, the script returns 1; otherwise, the return value is 0. The pifacecad library comes with two handy functions that make good use of the navigation switch and the LCD. The LCDQuestion function can be used to display a question in the first row of the LCD with the possible answer shown in the second row (Listing 5).

Listing 5

Using LCDQuestion

01 #!/usr/bin/python
02 import pifacecad
03 from pifacecad.tools.question import LCDQuestion
04 question = LCDQuestion(question="What do you like?", answers=['Ramen', \
   'Sushi', 'Sake'])
05 result = question.ask()
06 print (result)

You can then use the navigation switch to cycle through answers and select the entry you want by pressing the navigation switch. The result = question.ask() statement in the script returns the value of the selected answer (0 for Ramen, 1 for Sushi, and 2 for Sake). By extending this script, you can transform Raspberry Pi into a quiz machine with just a dash of Python code.

The LCDScanf function can be particularly useful for creating interactive menus, because it allows you to display, navigate, and select values. Using the function to display predefined values and read the chosen item is easy, as shown in Listing 6.

Listing 6

Using LCDScanf

01 #!/usr/bin/python
02 import pifacecad
03 from pifacecad.tools.scanf import LCDScanf
04 cad = pifacecad.PiFaceCAD()
05 scanner = LCDScanf("Value: %m%r", custom_values=('1', '3', '5', '7'))
06 value = str(scanner.scan())
07 result = value.strip("[']")
08 print (result)

In the script, the LCDScanf function returns the selected value wrapped in single quotes (e.g., '3', '5', etc.), so this script uses the result = value.strip("[']") statement to strip the quotes. The rest of the script is pretty much self-explanatory. Cycling through the values and selecting the desired one is done using the navigation switch. Press the switch to enter the select mode, then move the switch to the right and left to select the value you want. Press the switch again to return to the input mode. Then, use the switch to move the cursor to the right arrow on the screen and press the switch again to confirm the selection.

Final Word

Adding the PiFaceCAD board to a Raspberry Pi opens a whole new world of possibilities and lets you build a wide range of advanced projects that require basic input and provide visual feedback. From a web weather station and multichannel internet radio to a quiz game device and programmable camera remote control – your options are limited only by your imagination and coding skills.

Infos

  1. PiFace Control and Display: http://www.piface.org.uk/products/piface_control_and_display
  2. HD44780 LCD user-defined graphics: http://www.quinapalus.com/hd44780udg.html

Buy this article as PDF

Express-Checkout as PDF

Pages: 4

Price $2.95
(incl. VAT)

Buy Raspberry Pi Geek

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content