For part two of the Dial-A-Song project, I’m going to go through the hookup of the phone’s keypad so that it can act as an input to the Raspberry Pi.

The first thing to do was remove the short ribbon cable that came on the keypad and replace it with something a little longer so I could more easily hook it up to the Pi. Here’s the old ribbon cable:

Dial Pad and Tone Generator

And now with the new, more colorful, cable:

Keypad Wiring

On the other end, I attached a 2×5 IDC female header (I didn’t have a 2×4, so there’s a couple wasted pins). This is what will eventually connect to the Pi interface board I’ll create, but for now I mocked up a breakout board (the green perf-board) so I could connect it to a breadboard along with Adafruit’s great “Cobbler” kit.

The keypad’s internal wiring is setup as shown below (which the red wire being pin 1 and increasing to the left, from the image above):

  5 6 7

Most matrix keypads are very similar so, the keypad pins should be connected to the Raspberry Pi GPIO as follows:

Pad | Pi
1   - 25
2   - 24
3   - 23
4   - 18
5   - 22
6   - 17
7   - 4

Now for the software. Originally, I was going to use a library designed for specifically this purpose. It did exactly what it said it would with the exception that it uses polling to detect the keypads. This works, but required a significant amount of the CPU resources to get any decent response time. Often around 80%. This was not acceptable.

So, I decided to try converting the library to use the interrupt capability of the RPi.GPIO library that comes pre-installed on Raspbian. It took a little fiddling because the Pi GPIO pins are really susceptible to noise making button debouncing a real issue. But in the end, it works quite well:

import RPi.GPIO as GPIO
import time

class keypad():
    def __init__(self, callback):
        self._count = 0
        self._inInterrupt = False
        self._callback = callback

        # CONSTANTS 
        self.KEYPAD = [

        #hook the rows (1,4,7,*) to these GPIO pins
        self.ROW         = [18,23,24,25]
        #hook the columns (1,2,3) to these GPIO pins
        self.COLUMN      = [4,17,22]


    def __colInt(self, channel):
        time.sleep(0.05) #give it a moment to settle
        if GPIO.input(channel) > 0:

        #remove interrupts temporarily
        for c in range(len(self.COLUMN)):

        #get column number
        colVal = -1
        for c in range(len(self.COLUMN)):
            if channel == self.COLUMN:
                colVal = c

        #continue if valid column (it should always be)
        if colVal >=0 and colVal < len(self.COLUMN):

            #set rows as intputs
            for r in range(len(self.ROW)):
                GPIO.setup(self.ROW[r], GPIO.IN, pull_up_down=GPIO.PUD_UP)

            #set triggered column as low output
            GPIO.setup(channel, GPIO.OUT, initial=GPIO.LOW)

            # Scan rows for pushed key/button
            rowVal = -1
            for r in range(len(self.ROW)):
                tmpRead = GPIO.input(self.ROW[r])
                if tmpRead == 0:
                    rowVal = r

            #continue if row is valid (possible that it might not be if the key was very quickly released)
            if rowVal >= 0 and rowVal < len(self.ROW):
                #send key info right away
                #This avoids nasty boucning errors when the key is released
                #By waiting for the rising edge before re-enabling interrupts it 
                #avoids interrupts fired due to bouncing on key release and 
                #any repeated interrupts that would otherwise fire.
                    GPIO.wait_for_edge(self.ROW[rowVal], GPIO.RISING)
                except RuntimeError:

                print "Invalid Row!"
            print "Invalid Col!"

        #re-enable interrupts

    def __changeWrapper(self, channel):
        #if there is already another interrupt going on (multiple key press or something)
        #return right away to avoid collisions
        if self._inInterrupt:

        self._inInterrupt = True
        self.__colInt(channel) #handle the actual interrupt
        self._inInterrupt = False

    def __setInterruptMode(self):
        #set the first row as output low
        #only first one needed as it will ground to all columns
        for r in range(len(self.ROW)):
            GPIO.setup(self.ROW[r], GPIO.OUT, initial=GPIO.LOW)

        #set columns as inputs and attach interrupt handlers on rising edge
        for c in range(len(self.COLUMN)):
            GPIO.setup(self.COLUMN[c][/c], GPIO.IN, pull_up_down=GPIO.PUD_UP)
            GPIO.add_event_detect(self.COLUMN[c][/c], GPIO.FALLING, bouncetime=250, callback=self.__changeWrapper)

    def cleanup(self):
        print "Cleanup done!"

It's super simple to use as you can see from the code below. Instantiate the class with a callback function and that function gets called when there's a keypress on the pad. Just note that the callback will be running on the context of a different thread from the main thread. While it uses interrupts, RPi.GPIO cheats a little bit and the interrupts are actually running on background threads and so will the callback. Not usually a big problem but something to be aware of.

import time     
if __name__ == '__main__':
    def keypadCallback(value):
        print "Keypad: " + value

    key = keypad(keypadCallback)

        while True:

    except KeyboardInterrupt:

You can grab the full library and find any updates to it on GitHub.
That's all for now. Check back soon for more progress on Dial-A-Song!

Earlier this week, we got the great news that we have been accepted to the North Carolina Maker Faire. We’re absolutely ecstatic to get to share some of our projects with the public but it’s also been a great push to get some other projects done. I’ve had this particular project bouncing around my head for a couple of years now. I call it Dial-A-Song.

Much of the inspiration came from They Might Be Giants, who used to leave recordings of their songs on their answering machine, which could be listened to by calling (718) 387-6962. So, I wanted to combine a little of that with a phone tree menu to give the feel of calling in to a phone service to listen to music of your choice. Yes, it’s a little ridiculous, but why else would I be building it.

As a way of documenting the project and an extra push to keep working on it, I’m going to be writing up a build log in several parts as the build progresses.

So, first, the desired specs:

  • Completely enclosed in an old phone
  • Music plays over the headset speaker.
  • Raspberry Pi as the brains
  • Automatically index all music
  • Choose 10 random songs when the phone is picked up and make them available via the menu
  • Text to speech for the menu
  • Network capable for remote control

In part 1, I’ll deal with the phone itself. I really wanted to use an old pay-phone, but good condition models were well over $200, much more than I wanted to spend. So I went for the next best thing:

The Red Phone

Who doesn’t want a big red phone on their desk? Only important calls come over a red phone. I found this one on eBay for about $20 and it’s fully functional… now let’s gut it.

I started by removing the two large, flathead screws on the bottom metal plate. Once out, the entire top casing simply lifts off. As you can see from the interior picture, there’s really not much to these old phones. One PCB on the bottom, another beneath the dial pad, and the ringer assembly, which had to go. I would have loved to keep the ringer intact and actually use it but it takes up too much space and older phones like this run on a higher voltage than I would be working with. They typically run at 48V DC when idle, but a 90V 20Hz AC current is required to actually make the ringer work. So, out it came.

The main board had to go next, as it is really of no use. The only things from the phone I plan on using are the dial pad, the handset and the phone line input (for power and network). I was surprised to see how little was actually on the main board and that it was mostly there just to hook up all the other components of the phone… with removable spade connectors no less. This was definitely a hand-assembled product. The truly don’t make things like this anymore! The only active components on this board are likely for the ringer since it’s the only thing using AC current, making the small transformer and diodes a give-away to their purpose. No matter… to the parts bin it goes.

Dial Pad and Tone Generator

Next to come off is the dial pad assembly. Here’s where the electronics actually get a little interesting. The IC chip on the left is the HM9102C tone generator, responsible for generating the DTMF tones that make a “touch tone” phone system work. The IC reads the dial pad key presses and generates the corresponding tone that gets sent over the phone line. Each row on the dial pad represents a low frequency tone and each column a high frequency. So when a key is pressed, the chip creates a single tone from the two frequencies represented by the row and column of that key, hence the term “dual-tone, multi-frequency” or DTMF. But I don’t need this either – I’m just going to fake the tone sounds in software since they aren’t needed – so off to the parts bin with this board as well.

The dial pad, however, I do need. Fortunately, a little probing with a multimeter shows that it’s wired up like any other matrix keypad ever made. Even better, there’s already a python library for the Raspberry Pi that handles all the heavy lifting of reading the key presses. More on hooking this up in a future post.

Hang Up Relay

Next is the hang-up mechanism. It’s actually much more complex than I was expecting, as it includes 3 separate internal relays. The first (left most) has two switch contacts, one is open when the mechanism is down and the other when it is up. The middle relay opens the circuit when the mechanism is down whereas the right-most relay closes the circuit. Each obviously has a specific purpose, such as connecting the phone line to the handset speaker and mic. But I’m not sure which is which. Fortunately, I only need one of them and don’t really care which direction it goes. I just need to detect a state change via one of the Raspberry Pi GPIO pins and handle it accordingly in the software.

Phone Handset

Finally, for this post anyways, is the handset itself. I was a little surprised to see that it had a built in volume control (the wheel in the middle of the handle)… I’ll have to see if there is some way to actually make this work. Unfortunately, I won’t be able to use the volume circuit as is, or the speaker, because they are both designed to run on 48V DC. Whereas I plan to just connect it all to the 1/8″ audio jack on the Raspberry Pi. The major problem with the speaker is that, as a quick check with my multimeter showed, it has an impedance of over 100 ohms! It makes sense given the voltage it is supposed to run at but that is huge compared to the typical 4-8 ohms of modern speakers. So, instead, I’ll keep the wiring but replace the speaker with one from an old pair of headphones. Likely with both the right and left signals going to the same speaker.

That’s all for now. As this project continues I will post new articles following the progress. Stay tuned!