Source

HD44780 & MCP23017 / hd44780.py

#! /usr/bin/python

# A simple Python command line tool to control an MCP23017 I2C IO Expander
# By Nathan Chantrell http://nathan.chantrell.net
# GNU GPL V3 

import smbus
import sys
import getopt
from time import sleep
import os

bus = smbus.SMBus(1) # For revision 1 Raspberry Pi, change to bus = smbus.SMBus(1) for revision 2.

address = 0x20 # I2C address of MCP23017
bus.write_byte_data(0x20,0x00,0x00) # Set all of bank A to outputs 
bus.write_byte_data(0x20,0x01,0x00) # Set all of bank B to outputs 

a = [(0x12, 0), (0x12, 1), (0x12, 2), (0x12, 3), (0x12, 4), (0x12, 5), (0x12, 6), (0x12, 7)]
b = [(0x13, 0), (0x13, 1), (0x13, 2), (0x13, 3), (0x13, 4), (0x13, 5), (0x13, 6), (0x13, 7)]

data_pins = [b[7], b[6], b[4], b[3], a[3], a[4], a[6], a[7]]

def high((register, pin)):
	value = bus.read_byte_data(address, register)
	value |= (1 << pin)
	bus.write_byte_data(address, register, value)

def low((register, pin)):
	value = bus.read_byte_data(address, register)
	value &= ~(1 << pin)
	bus.write_byte_data(address, register, value)

def pulse():
	low(a[2])
	sleep(0.0001)
	high(a[2])
	sleep(0.0001)
	low(a[2])
	sleep(0.0001)

def write8bits(bits, char_mode=False):
	sleep(0.001)
	if (char_mode):
		high(a[1])
	else:
		low(a[1])

	for pin in data_pins:
		low(pin)

	for i in range(8):
		if (bits & (1 << i)) == 1 << i:
			high(data_pins[i])
	pulse()
	low(a[1])

def write(string):
		for c in string:
				write8bits(ord(c), True)

def clear():
	write8bits(0x01)

def home():
	write8bits(0x02)

def initialize():
	bus.write_byte_data(address, 0x12, 0)
	bus.write_byte_data(address, 0x13, 0)
	sleep(0.020)

	high(a[0])
	high(b[0])
	high(b[1])
	sleep(0.020)

	write8bits(0x30)
	sleep(0.020)
	write8bits(0x30)
	sleep(0.020)
	write8bits(0x30)
	sleep(0.020)
	write8bits(0x3b)
	write8bits(0x08)
	write8bits(0x01)
	write8bits(0x0c)
	write8bits(0x06)