Showing posts with label MCP23008. Show all posts
Showing posts with label MCP23008. Show all posts

Monday, August 19, 2013

Python Matrix Keypad Package

I packaged up the Matrix Keypad code into a downloadable and installable PyPI package. Let me know if you have any issues but it seems download and install well with PIP and once you make the symlinks to the adafruit code you should be good to go.

Also if there is anyone that has a Beagle Bone that can help me port this over to it aswell I would appreciate it. I've had a few requests but I don't own one yet to do the work on. (unless someone ones to send me one :) )

https://pypi.python.org/pypi/matrix_keypad

Introduction

Python Library for Matrix Keypads. Written and tested on a Model B Raspberry Pi. Supports both a 3x4 and 4x4 keypad included
Current Version:
 v1.1.1
Project Page:Project_Page
PyPI page:PyPI_Page

Author

Prerequisites

If the I2C Port expander MCP23017 or MCP23008 is being used, the Adafruit Python library for I2C and the MCP will need to be installed.
You can clone the whole library like so:
git clone https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code.git
or the two files needed can be pulled out, Adafruit_I2C.py & Adafruit_MCP230xx.py.

Install

You can use the source from just downloading the files or Install it as a library via PIP:
pip install matrix_keypad
After the install you will need to create links to the Adafruit I2C and MCP230xx code since they are not installed as packages.:
sudo ln -s [path to Adafruit python cod]/AdafruitMCP230xx/*.py /usr/local/lib/python2.7/dist-packages/matrix_keypad
Note: you will have to change the part in the brackets and maybe the path to the where the matrix keypad package is

Files Included

README.txt
LICENSE.txt
setup.py
matrix_keypad/
    __init__.py
    matrix_keypad_RPi_GPIO.py
    matrix_keypad_MCP230xx.py
    matrix_keypad_demo.py
    matrix_keypad_demo2.py

Usage

See the demo scripts included to see this all in action.
To call the library select which one you intend to use and use the correct line:
from matrix_keypad import MCP230xx
or:
from matrix_keypad import RPi_GPIO
Then initialize and give the library a short name so it is easier to reference later. For the MCP version:
kp = MCP230xx.keypad(address = 0x21, num_gpios = 8, columnCount = 4
The variables here are the I2C address, then if you are using the MCP23017 or MCP23008 you have to put the number of GPIO pin avaialable (default is 8), Then the "columnCount" is 3 for the 4x3 keypads and 4 for the 4x4 keypads.
For the standard GPIO version you only have to reference the 'column count if you want to change it to the 4x4, it defaults at the 3x4:
kp = RPi_GPIO.keypad(ColumnCount = 4)
It is possible to just check to see if a digit is currently pressed.:
checkKeypad = kp.getKey()
Or a simple function to call the keypad library and loop through it waiting for a digit press
def digit():
    # Loop while waiting for a keypress
    digitPressed = None
    while digitPressed == None:
        digitPressed = kp.getKey()
    return digitPressed

Version History

v0.1.0:
Initial Scripts
v1.0.0:
Initial package build
v1.0.1:
Initial package build and push to PyPI
v1.0.2:
Updating the matrix_keypad_demo2.py to demo selecting the 4x4 keypad
v1.0.3:
Moved Version Log in README
Updated README Links
v1.0.4:
Updated References to include the PiLarm code as the inspiration for the "...demo2.py" code
v1.0.5:
Updates to the code in both main libs to fix some indenting and other issues from coping the code from blogger to a text file.
Updates to the keypad picking section for the constants to make it actually work
v1.0.6:
Fixes to more indenting issues. :(
v1.1.0:
Updated main libs and the demo code.
Added install directions to handle the links to the adafruit code
v1.1.1:
Updated ...demo.py and demo2.py to reflect new package name.
Updated README as well

Code References

Column and Row scanning adapted from Bandono's matrixQPI which is wiringPi based.
matrix_keypad_demo2.py is based on some work that Jeff Highsmith had done in making his PiLarm that was featured on Make.

Monday, May 13, 2013

Using 3x4 matrix keypad with the Raspberry Pi

UPDATE 8/23/13
This page will stay since it explains the original scripts but I've made a number of updates and have packaged them up on the PyPI so they are easy to maintain for me and to distribute and install for everyone else. Let me know if there are any issues and I'll attempt to take care of them as time allows.
https://pypi.python.org/pypi/matrix_keypad
http://crumpspot.blogspot.com/p/keypad-matrix-python-package.html

Another module of my alarm interface is done. I picked up a 3x4 matrix keypad from Adafruit (http://www.adafruit.com/products/419) But couldn't find any good python code examples for it's use. I was able to find a few examples that lead me down the right path in terms of scanning rows first as inputs and then swapping pins to scan the columns. I wrote two libraries, the first just uses 7 of the Raspberry Pi's GPIO pins then I also wrote one that works for the MCP23008 chip since I'm really in a mode of saving pins when I can :) Then also just wrote a demo script to show calling the libraries and their use.

Here is the code as it stands now, I have some ideas on how to change it to be better but this is fully working for now.

UPDATE: I received a 4x4 keypad to test changes to the script and it worked like a charm once I changed the keypad and the Row and Column values like so:
KEYPAD = [
[1,2,3,"A"],
[4,5,6,"B"],
[7,8,9,"C"],
["*",0,"#","D"]
]
ROW = [7,6,5,4]
COLUMN = [3,2,1,0]


matrixKeypad_RPi_GPIO.py:


# #####################################################
# Python Library for 3x4 matrix keypad using
# 7 of the avialable GPIO pins on the Raspberry Pi. 
# 
# This could easily be expanded to handle a 4x4 but I 
# don't have one for testing. The KEYPAD constant 
# would need to be updated. Also the setting/checking
# of the colVal part would need to be expanded to 
# handle the extra column.
# 
# Written by Chris Crumpacker
# May 2013
#
# main structure is adapted from Bandono's
# matrixQPI which is wiringPi based.
# https://github.com/bandono/matrixQPi?source=cc
# #####################################################

import RPi.GPIO as GPIO

class keypad():
    # CONSTANTS   
    KEYPAD = [
    [1,2,3],
    [4,5,6],
    [7,8,9],
    ["*",0,"#"]
    ]
    
    ROW         = [18,23,24,25]
    COLUMN      = [4,17,22]
    
    def __init__(self):
        GPIO.setmode(GPIO.BCM)
    
    def getKey(self):
        
        # Set all columns as output low
        for j in range(len(self.COLUMN)):
            GPIO.setup(self.COLUMN[j], GPIO.OUT)
            GPIO.output(self.COLUMN[j], GPIO.LOW)
        
        # Set all rows as input
        for i in range(len(self.ROW)):
            GPIO.setup(self.ROW[i], GPIO.IN, pull_up_down=GPIO.PUD_UP)
        
        # Scan rows for pushed key/button
        # A valid key press should set "rowVal"  between 0 and 3.
        rowVal = -1
        for i in range(len(self.ROW)):
            tmpRead = GPIO.input(self.ROW[i])
            if tmpRead == 0:
                rowVal = i
                
        # if rowVal is not 0 thru 3 then no button was pressed and we can exit
        if rowVal <0 data-blogger-escaped-or="" data-blogger-escaped-rowval="">3:
            self.exit()
            return
        
        # Convert columns to input
        for j in range(len(self.COLUMN)):
                GPIO.setup(self.COLUMN[j], GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        
        # Switch the i-th row found from scan to output
        GPIO.setup(self.ROW[rowVal], GPIO.OUT)
        GPIO.output(self.ROW[rowVal], GPIO.HIGH)

        # Scan columns for still-pushed key/button
        # A valid key press should set "colVal"  between 0 and 2.
        colVal = -1
        for j in range(len(self.COLUMN)):
            tmpRead = GPIO.input(self.COLUMN[j])
            if tmpRead == 1:
                colVal=j
                
        # if colVal is not 0 thru 2 then no button was pressed and we can exit
        if colVal <0 data-blogger-escaped-colval="" data-blogger-escaped-or="">2:
            self.exit()
            return

        # Return the value of the key pressed
        self.exit()
        return self.KEYPAD[rowVal][colVal]
        
    def exit(self):
        # Reinitialize all rows and columns as input at exit
        for i in range(len(self.ROW)):
                GPIO.setup(self.ROW[i], GPIO.IN, pull_up_down=GPIO.PUD_UP) 
        for j in range(len(self.COLUMN)):
                GPIO.setup(self.COLUMN[j], GPIO.IN, pull_up_down=GPIO.PUD_UP)
        
if __name__ == '__main__':
    # Initialize the keypad class
    kp = keypad()
    
    # Loop while waiting for a keypress
    digit = None
    while digit == None:
        digit = kp.getKey()
    
    # Print the result
    print digit  

matrixKeypad_MCP230xx.py

# #####################################################
# Python Library for 3x4 matrix keypad using
# the MCP23008 chip via I2C from the Raspberry Pi.
# 
# This could easily be expanded to handle a 4x4 but I 
# don't have one for testing. The KEYPAD constant 
# would need to be updated. Also the setting/checking
# of the colVal part would need to be expanded to 
# handle the extra column.
# 
# Written by Chris Crumpacker
# May 2013
#
# main structure is adapted from Bandono's
# matrixQPI which is wiringPi based.
# https://github.com/bandono/matrixQPi?source=cc
# #####################################################

from Adafruit_MCP230xx import Adafruit_MCP230XX

class keypad(Adafruit_MCP230XX):
    # Constants
    INPUT       = 0
    OUTPUT      = 1
    HIGH        = 1
    LOW         = 0
    
    KEYPAD = [
    [1,2,3],
    [4,5,6],
    [7,8,9],
    ["*",0,"#"]
    ]
    
    ROW         = [6,5,4,3]
    COLUMN      = [2,1,0]
    
    def __init__(self, address=0x21, num_gpios=8):
        
        self.mcp2 = Adafruit_MCP230XX(address, num_gpios)
        
    def getKey(self):
        
        # Set all columns as output low
        for j in range(len(self.COLUMN)):
            self.mcp2.config(self.COLUMN[j], self.mcp2.OUTPUT)
            self.mcp2.output(self.COLUMN[j], self.LOW)
        
        # Set all rows as input
        for i in range(len(self.ROW)):
            self.mcp2.config(self.ROW[i], self.mcp2.INPUT)
            self.mcp2.pullup(self.ROW[i], True)
        
        # Scan rows for pushed key/button
        # valid rowVal" should be between 0 and 3 when a key is pressed. Pre-setting it to -1
        rowVal = -1
        for i in range(len(self.ROW)):
            tmpRead = self.mcp2.input(self.ROW[i])
            if tmpRead == 0:
                rowVal = i
                
        # if rowVal is still "return" then no button was pressed and we can exit
        if rowVal == -1:
            self.exit()
            return
        
        # Convert columns to input
        for j in range(len(self.COLUMN)):
            self.mcp2.config(self.COLUMN[j], self.mcp2.INPUT)
        
        # Switch the i-th row found from scan to output
        self.mcp2.config(self.ROW[rowVal], self.mcp2.OUTPUT)
        self.mcp2.output(self.ROW[rowVal], self.HIGH)
        
        # Scan columns for still-pushed key/button
        colVal = -1
        for j in range(len(self.COLUMN)):
            tmpRead = self.mcp2.input(self.COLUMN[j])
            if tmpRead == 1:
                colVal=j
        
        if colVal == -1:
            self.exit()
            return
              
        # Return the value of the key pressed
        self.exit()   
        return self.KEYPAD[rowVal][colVal]
            
    def exit(self):
        # Reinitialize all rows and columns as input before exiting
        for i in range(len(self.ROW)):
                self.mcp2.config(self.ROW[i], self.INPUT) 
        for j in range(len(self.COLUMN)):
                self.mcp2.config(self.COLUMN[j], self.INPUT)
        
if __name__ == '__main__':
    # Initialize the keypad class
    kp = keypad()
    
    # Loop while waiting for a keypress
    r = None
    while r == None:
        r = kp.getKey()
        
    # Print the result
    print r  

Demo code, matrixKeypad_test.py

# #####################################################
# Demo script showing the use of the Python 
# matrix Keypad library for both the Raspberry Pi
# GPIO and the MSP230xx I2C Chip set.
#
# Librarys needed:
# matrixKeypad_MCP230xx.py or matrixKeypad_RPi_GPIO.py
#
# Also needed is the Adafruit python libraries for the 
# MCP230xx chips (Adafruit_MCP230xx.py) and I2C (Adafruit_I2C.py)
# 
# Written by Chris Crumpacker
# May 2013
#
# #####################################################

from matrixKeypad_MCP230xx import keypad
#from matrixKeypad_RPi_GPIO import keypad
from time import sleep

# Initialize the keypad class
kp = keypad()

def digit():
    # Loop while waiting for a keypress
    r = None
    while r == None:
        r = kp.getKey()
    return r 

print "Please enter a 4 digit code: "

# Getting digit 1, printing it, then sleep to allow the next digit press.
d1 = digit()
print d1
sleep(1)

d2 = digit()
print d2
sleep(1)

d3 = digit()
print d3
sleep(1)

d4 = digit()
print d4

# printing out the assembled 4 digit code.
print "You Entered %s%s%s%s "%(d1,d2,d3,d4) 

Monday, May 6, 2013

Using 20x4 LCD displays with the MCP23017 and Raspberry Pi

Adafruit sells a nice I2C connected 16x2 LCD "plate" to go on top of the RPi that also includes a few buttons. See: http://www.adafruit.com/products/1110 They also include the python library to run it and functions that are pretty easy to use. See: https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code/tree/master/Adafruit_CharLCDPlate

Now that's all well and good but as part of an upcoming project I am planning I have bigger needs. First LCD size. I want to run the 20x4 size so I can display outputs on the first 3 lines and then use the fourth line for menu navigation. Second I am going to be using a 4x3 keypad, a "D-Pad" style button setup,a buzzer,  and a few status LEDs. All of this is going to require one 16 pin (28dip)digital I/O expansion chip, MCP23017 to drive the display, the d-pad, buzzers and LEDs. Then an 8pin (18dip) MCP23008 chip to handle the 4x3 keypad. On top of that it needs to be almost 70' away. 

So I used their good work in the coding department to jump off from. Obviously since the product limits to the use of the 16x2 displays due to physical space the code needed to be optimized to handle differing display sizes. I went a little beyond that and added some support for handling longer text strings that would usually overflow into the buffer, and in the case of the 4 line displays that means any text in the buffer for line one appears on line 3... :(


Running the example code provided below to demonstrate the EoL handling.

Here is the new "message" function from the Adafruit_CharLCDPlate.py script/class.  I just checked in to their Github repo. One thing to note is that this in no way changes the functionality for the normal plate. Any existing scripts will function just like before. But with the addition of handling 4 line displays seamlessly and then all of the EoL features can be added be putting a 1 or 2 in the message function call after your test to print. My github fork


    def message(self, text, limitMode = 0):
            """ Send string to LCD. Newline wraps to next line"""
            lines = str(text).split('\n')       # Split at newline(s)
            for i, line in enumerate(lines):    # For each substring...
                if i == 1:                      # If newline(s),
                    self.write(0xC0)             # set DDRAM address to 2nd line
                elif i == 2:
                    self.write(0x94)
                elif i >= 3:
                    self.write(0xD4)
                """Now depending on the limit mode set by the function call this will handle """
                lineLength = len(line)
                limit = self.numcols
                if limitMode <= 0: 
                    self.write(line, True)     
                elif lineLength >= limit and limitMode == 1:
                    '''With the limit mode set to 1 the line is truncated 
                    at the number of columns available on the display'''
                    limitedLine = line[0:self.numcols]
                    self.write(limitedLine, True)  
                elif lineLength >= limit and limitMode == 2:
                    '''With the limit mode set to 2 the line is truncated 
                    at the number of columns minus 3 to add in an elipse'''
                    limitedLine = line[0:self.numcols-3]+'...'
                    self.write(limitedLine, True)
                elif lineLength >= limit and limitMode >= 3:
                    '''Future todo, add in proper, "line after line" cariage return'''
                else:
                    self.write(line, True)

I also had to add the "self.numlines = lines" to the begin function so I could use the column count.

    def begin(self, cols, lines):
        self.currline = 0
        self.numlines = lines
        self.numcols = cols
        self.clear()

I also spent some time making an example script to leverage this new message function as well as some of the other standard built in functions. Here is my example script on github

#!/usr/bin/python

#----------------------------------------------------------------
# Author: Chris Crumpacker                               
# Date: May 2013
#
# A demo of some of the built in helper functions of 
# the Adafruit_CharLCDPlate.py and Using the EoL_HandlingAnd4LineSupport.py
# 
# Using Adafruit_CharLCD code with the I2C and MCP230xx code as well
#----------------------------------------------------------------

numcolumns = 20
numrows = 4

from time import sleep
from Adafruit_CharLCDPlate import Adafruit_CharLCDPlate

lcd = Adafruit_CharLCDPlate()

lcd.begin(numcolumns, numrows)

lcd.backlight(lcd.ON)
lcd.message("LCD 20x4\nDemonstration")
sleep(2)

while True:
    #Text on each line alone.
    lcd.clear()
    lcd.setCursor(0,0)
    lcd.message("Line 1")
    sleep(1)
    
    lcd.clear()
    lcd.setCursor(0,1)
    lcd.message("Line 2")
    sleep(1)
    
    lcd.clear()
    lcd.setCursor(0,2)
    lcd.message("Line 3")
    sleep(1)
    
    lcd.clear()
    lcd.setCursor(0,3)
    lcd.message("Line 4")
    sleep(1)
    
    # Using the "\n" new line marker
    lcd.clear()
    lcd.setCursor(0,0)
    lcd.message("Line 1")
    sleep(1)
    
    lcd.clear()
    lcd.setCursor(0,0)
    lcd.message("Line 1\nLine 2")
    sleep(1)
    
    lcd.clear()
    lcd.setCursor(0,0)
    lcd.message("Line 1\nLine 2\nLine 3")
    sleep(1)
    
    lcd.clear()
    lcd.setCursor(0,0)
    lcd.message("Line 1\nLine 2\nLine 3\nLine 4")
    sleep(1)
        
    # Auto line limiting by length as to not overflow the display
    # This is line by line and does not to any caraige returns
    lcd.clear()
    lcd.setCursor(0,0)
    lcd.message("This String is 33 Characters long",1)
    sleep(2)    
    
    lcd.clear()
    lcd.setCursor(0,0)
    lcd.message("This String has elpise",2)
    sleep(2)    
    
    #Scroll text to the right
    messageToPrint = "Scrolling Right"
    i=0
    while i<20:
        lcd.clear()
        lcd.setCursor(0,0)
        suffix = " " * i
        lcd.message(suffix + messageToPrint,1)
        sleep(.25)
        i += 1
    
    # Scroll test in from the Left
    messageToPrint = "Scrolling Left"
    i=20
    while i>=0:
        lcd.clear()
        lcd.setCursor(0,0)
        suffix = " " * i
        lcd.message(suffix + messageToPrint,1)
        sleep(.25)
        i -= 1
    sleep(2)  
    
    # Printing text backwards, NOT right justified
    lcd.clear()
    lcd.setCursor(0,0)
    lcd.message("Right to left:")
    lcd.setCursor(10,1)
    lcd.rightToLeft()
    lcd.message("Testing")
    sleep(2)
    
    # Printing normally from the middle of the line
    lcd.clear()
    lcd.setCursor(0,0)
    lcd.message("Left to Right:")
    lcd.setCursor(10,1)
    lcd.message("Testing")
    sleep(2)
    
    # Enabling the cursor and having it blink
    lcd.clear()
    lcd.setCursor(0,0)
    lcd.cursor()
    lcd.blink()
    lcd.message("Cursor is blinking")
    lcd.setCursor(0,1)
    sleep(3)
    lcd.noCursor()
    lcd.noBlink()
    
    # Turning the backlight off and showing a simple count down
    lcd.clear()
    lcd.setCursor(0,0)
    lcd.message("Backlight off in")
    lcd.setCursor(0,3)
    lcd.message("Back on in 3sec")
    lcd.setCursor(17,0)             #Reseting the cursor here keeps us from having to clear the screen, this over writes the previous character
    lcd.message("3")
    sleep(1)
    
    lcd.setCursor(17,0)
    lcd.message("2")
    sleep(1)
    
    lcd.setCursor(17,0)
    lcd.message("1")
    sleep(1)
    
    lcd.backlight(lcd.OFF)
    lcd.clear()
    lcd.setCursor(0,0)
    sleep(3)
    lcd.backlight(lcd.ON)
    lcd.message("Backlight on")