This is the first of a couple libraries to come that greatly simplify using I2c capable devices on the Raspberry Pi with Python. Although there is a couple code examples out there, the intent of this library was to be flexible enough to allow for the various types of I2c LCD devices available. The main variation in these devices are the pin layout between the I2c IO expander (ex. PCF8574*) and the LCD HD44780 controller; the library can be configured at instantiation to accomodate any of these pin layouts. Additionally it has simple functions for home, clear, cursor position and backlight control.
from i2clibraries import i2c_lcd
from time import *
# Configuration parameters
# I2C Address, Port, Enable pin, RW pin, RS pin, Data 4 pin, Data 5 pin, Data 6 pin, Data 7 pin, Backlight pin (optional)
lcd = i2c_lcd.i2c_lcd(0x27,0, 2, 1, 0, 4, 5, 6, 7, 3)
# If you want to disable the cursor, uncomment the following line
# lcd.command(lcd.CMD_Display_Control | lcd.OPT_Enable_Display)
lcd.writeString("Python I2C LCD")
lcd.writeString("For the Pi")
Determining The Pin Layout
Determining what the correct pin numbers is crucial for the library to function. This should be available from the vendor you purchase the LCD or could be acquired from the schematic. Additionally most vendors will have example Arduino code which could be used to determine the pin layout. Here is an example of Arduino code and how to interpret it.
# The order of the parameters is the same as the common Arduino library
# with the addition of a port parameter after the I2C address and a
# backlight pin at the end
The port is easy to determine. The original Pi is 0 and the new version is 1.
Installing the I2C Libraries
Note: This library has changed and now requires the Quick2Wire libraries. To use a legacy smbus version, use i2c_lcd_smbus.py.
Instructions for installing the Think Bowl I2C Libraries are here.
Turns the backlight on if available
Turns the backlight off if available
Clears text from screen
Sends a command function to LCD. Variables with the different commands and options are available in the object.
Returns cursor to top left position
Sets the cursor to the given line and position on that line. Lines are 1-4 and positions are 0-19.
Writes a single character at the current cursor position
Writes a string to the screen starting at the current postion