raspberry pi lcd display i2c free sample
This repository contains all the code for interfacing with a 16x2 character I2C liquid-crystal display (LCD). This accompanies my Youtube tutorial: Raspberry Pi - Mini LCD Display Tutorial.
During the installation, pay attention to any messages about python and python3 usage, as they inform which version you should use to interface with the LCD driver. For example:
It is possible to define in CG RAM memory up to 8 custom characters. These characters can be prompted on LCD the same way as any characters from the characters table. Codes for the custom characters are unique and as follows:
For example, the hex code of the symbol ö is 0xEF, and so this symbol could be printed on the second row of the display by using the {0xEF} placeholder, as follows:
This demo uses ping and nc (netcat) to monitor the network status of hosts and services, respectively. Hosts and services can be modified by editing their respective dictionaries:
exchangerate-api.com / free.currencyconverterapi.com: There are a lot of currency apis but these ones offer free currency exchange info. Both are used, one as main, the other as backup. Requires an API key to use.
In order to use the script, you need to get API key tokens for both exchange rate services and the weather api. Once you"ve done that, edit the script to put your tokens in the USER VARIABLES section.
Internet of things (IoT) is fascinating. I am predominantly a web applications person. But sensors, LED display, chips, soldering and the collage of software with these “things” is exciting.
The credit card sized Raspberry Pi computer gives all the opportunity to experiment and explore IoT. I wrote getting started with IoT using Raspberry Pi and PHP a while back. Now I thought of extending that and write about my hobby projects that I do with Raspberry Pi.
Raspberry Pi is my hobby and I thought of sharing with you about these tiny projects. This will be a multi article series. Let us start with how to connect a I2C LCD display with the Raspberry Pi.
I2C is a serial bus developed by Philips. So we can use I2C communication and just use 4 wires to communicate. To do this we need to use an I2C adapter and solder it to the display.
I2C uses two bidirectional lines, called SDA (Serial Data Line) and SCL (Serial Clock Line) with 5V standard power supply requirement a ground pin. So just 4 pins to deal with.
When you buy the LCD module, you can purchase LCD, I2C adapter separately and solder it. If soldering is not your thing, then it is better to buy the LCD module that comes with the I2C adapter backpack with it.
The above image is backside of a 2004 LCD module. The black thing is the I2C adapter. You can see the four pins GND, VCC, SDA and SCL. That’s where the you will be connecting the Raspberry Pi.
Raspberry Pi GPIO pins are natively of 3.3V. So we should not pull 5v from Raspberry Pi. The I2C LCD module works on 5V power and to make these compatible, we need to shift up the 3.3V GPIO to 5V. To do that, we can use a logic level converter.
You might see RPIs connected directly to a 5V devices, but they may not be pulling power from RPI instead supplying externally. Only for data / instruction RPI might be used. So watch out, you might end up frying the LCD module or the RPI itself.
Why am I recommending the official power adapter! There is a reason to it. The cheap mobile adapters though guarantee a voltage, they do not provide a steady voltage. That may not be required in charging a cellphone device but not in the case of Raspberry Pi. That is the main reason, a USB keyboard or mouse attached does not get detected. They may not get sufficient power. Either go for an official power adapter or use the best branded one you know.
I have a headless setup. I am doing SSH from my MAC terminal and use VIM as editor. VNC viewer may occasionally help but doing the complete programming / debugging may not be comfortable. If you do not prefer SSH way, then you will need a monitor to plug-in to Raspberry Pi.
As you know my language of choice to build website is PHP. But for IoT with Raspberry Pi, let us use Python. Reason being availability of packages and that will save ton of effort. Low level interactions via serial or parallel interface is easier via Python.
Following code imports the RPLCD library. Then initializes the LCD instance. Then print the “Hello World” string followed by new line. Then another two statements. Then a sleep for 5 seconds and switch off the LCD backlight. Finally, clear the LCD screen.
In this C# electronics tutorial, you will write a .NET application to display text onto a 16x2 (or 20x4) LCD character display connected to a Raspberry Pi.
Using the I2C interface allows us to connect our LCD display using only two of the Raspberry Pi"s GPIO pins - namely the I2C clock and data lines. Connect any 5V power pin from the Raspberry Pi to the positive rail on your breadboard and connect a Ground pin to the negative rail.
Wire VDD of MCP23008 to the positive rail of the breadboard, and wire VSS to the ground rail. According to the datasheet, the RESET pin must be pulled high in order to active the device, so connect it to the positive rail.
I2C allows you to communicate with multiple devices on a single bus. All connected I2C devices must have a unique address. We can configure the address for our connected device by setting the value for the three address pins A0, A1, and A2. According to the datasheet, addressing for the MCP23008 I/O expander has four fixed bits (0b0100) followed by the values of the three address pins. In other words, there is an offset of 0X20. Pulling all the address pins low, for example, will result in a slave address of 0X20.
There are only a few LCD pins remaining to configure, and then we will get to the code. First, provide power to the board and enable the backlight. Pin 1 on my LCD display is labeled VSS. Connect this to the negative (ground) rail on the breadboard. Connect pin 2 of the character display (labeled VDD on mine) to the positive (5V) rail of the breadboard. Pin 15 is the anode (A) for the backlight power supply. Connect pin 15 to the positive rail. Then, connect Pin 16, the cathode (K), to the ground rail.
Create a new C# Console application. I will call mine RPiLcd. For this project, you will need to install the Iot.Device.Bindings Nuget package.Install-Package Iot.Device.Bindings
Configure an I2C device with address of 0x20 as you configured before. Also, add a driver for the MCP23008 chip using the same I2C device,using I2cDevice i2cDevice = I2cDevice.Create(new I2cConnectionSettings(1,0x20));
Next, create a new LCD device using the serial driver you just created. The pin numbers should correspond to the GPIO pin names of the MCP23008 that each corresponding LCD pin is connected to. If you are using a 20x4 LCD display, change Lcd1602 to Lcd2004.using var lcd = new Lcd1602(dataPins: new int[] { 0, 1, 2, 3 },
Now, let"s write something to the screen! It is good practice to clear the LCD to remove any residual artifacts. The SetCursorPosition() method allows you to move the cursor to different columns and different rows.lcd.Clear();
Though you may have configured your publish options to produce a single file, the extra library file must be pushed to your Raspberry Pi separately. You will find it in the same target location folder you defined in your publish profile settings (e.g. your project"s bin\Release\net5.0\publish\ directory). In a terminal window, change directory to the location above and push the files to your Raspberry Pi.scp RPiLcd pi@192.168.1.10:/home/pi/RPiLcd/
In this tutorial, you wrote a C# application to interface with the GPIO pins on a Raspberry Pi and drive an LCD character display. This was all made easy using the GPIO libraries made available in .NET 5. You also learned a technique for conserving input/output pins using an I/O expander like the MCP23008. In this case, you were able to use the serial capabilities of the chip to enable communication with an LCD displaying using an I2C interface.
In this project, we"ll see how to hook up a 16x2 Character I2C LCD module with a ProtoStax Enclosure for Raspberry Pi to display interesting information like the Pi"s IP Address, Date & Time, or any other information you would like to display!
TheProtoStax LCD Kit V2is a new Extension Kit from ProtoStax. It can be used to add a 16x2 Character I2C LCD module to any ProtoStax Enclosure. You simply replace the top of your existing ProtoStax Enclosure with the one from the kit with the LCD module installed, and you"ll have an enclosure with an LCD screen!
Firstly, mount the LCD screen from the kit to the Top Plate from the kit using the mounting hardware. Then, unscrew and remove the Top Plate from your ProtoStax Enclosure Raspberry Pi (A+/B+, 4B/Zero) and replace it with the LCD Kit Top Plate.
Since the LCD module that is used has an I2C adapter, you only need 2 I2C pins to communicate with it. Wiring is super easy.RPi 5v pin (physical pin 2) - LCD VCC
Next, we want to enable I2C on the Raspberry Pi (if it is not already enabled). You can do that using the raspi-config utility. Here are the steps to do so. You will first run$ sudo raspi-config
We are going to interact with the LCD using Python. To do that, we are going to use the install the necessary python packages - we use RPLCD and smbus (to use I2C to communicate with the LCD module).$ sudo pip3 install RPLCD
We"ll demonstrate printing the IP address and Date and Time on the LCD screen, using the Python program below. You can find the source code on the GitHub link below.
Assuming you"ve installed it in ProtoStax_RPi_LCD_Example/ under your home directory, launch the program thus:$ python3 /home/pi/ProtoStax_RPi_LCD_Example/lcd_ip.py
This displays the Date and Time on the first line, and the second line of the 16x2 display shows the IP address and hostname of the Raspberry Pi in a scrolling fashion (as the character count is longer than 16 characters, we have to resort to scrolling). The
If the network is down on unreachable, then the IP address and hostname will be empty - therefore with a quick glance you can tell about the connection status of your Raspberry Pi as well as know how to connect to it, if it is headless. Just use the IP address or use
Now we want to make sure that this script gets run when we boot up the computer. We therefore create a service (which we call lcd.service) and make sure that the service is enabled (this assumes that the lcd_ip.py Python script is in the /home/pi/ProtoStax_RPi_LCD_Example directory - adjust the path accordingly in the WorkingDirectory below)
When shutting down the computer, the service gets stopped, and the python script as part of cleanup will clear the LCD screen and turn off the backlight.
Of course, you can also use the LCD display to display other information. For example, you cancreate a stock ticker that shows a scrolling ticker of stock prices you are interested in
In previous posts I’ve covered using HD44780 16×2 and 20×4 LCD screens with the Raspberry Pi using Python. These are relatively easy to use but require a number of connections to be made to the Pi’s GPIO header. This setup can be simplified with the use of an I2C enabled LCD screen.
This requires a high level voltage (5V) and a low level voltage (3.3V) which the device uses as a reference. The HV pins can be connected to the screen and two of the LV pins to the Pi’s I2C interface.Level ShifterPiI2C Backpack
While experimenting I found that it worked fine without the level shifting but I couldn’t be certain this wasn’t going to damage the Pi at some point. So it’s probably best to play it safe!
The example script will allow you to send text to the screen via I2C. It is very similar to my scripts for the normal 16×2 screen. To download the script directly to your Pi you can use :wget https://bitbucket.org/MattHawkinsUK/rpispy-misc/raw/master/python/lcd_i2c.py
In order to use I2C devices you must enable the interface on your Raspberry Pi. This can be done by following my “Enabling The I2C Interface On The Raspberry Pi” tutorial. By default the I2C backpack will show up on address 0x27.
In this project I"ll use WiringPi I2C to interface an I2C LCD display module. This is an interface board with a small microcontroller that controls a HD44780 type liquid crystal display.
There are libraries for operating this device with Arduino but getting the actual operating codes to avoid the libraries was useless. I found a program in Python and ported that over to WiringPi and used C directly.
Above illustrates the type of connection in the module. (This is not the actual schematic, but can be programmed to do the same thing if one wanted to build their own.) One must write each command or data byte as two half bytes or nibbles. This is done using two small functions lcd_byte(int bits, int mode) and lcd_toggle_enable(int bits).
The above commands were used with Arduino C and Microchip PIC C and ported over to Raspberry Pi C. TypeFloat() and typeInt() functions use the sprintf() function to convert the integers and floats to as string. Then both are sent to typeln() function which needs a little explanation.
In fact we can send a simple text string director to the typeln() function: typeln("Hello world!"). lcdLoc() sets the cursor location for the next character even is programmed to display no blinking cursor. Ox80 (LINE1) is the address for ROW 0 COL 0 while 0xC0 (LINE2) is ROW 1 COL 0.
The function typeln() will output to the display via lcd_byte() function one character at a time incrementing the address pointer "s" until the null character is reached terminating the "while" loop.
Those ICs have 3 address inputs, which gives us 2^3=8 possible addresses. You can see the A0,A1,A2 pads. They"re pulled up to VCC by default, which makes them all 1s. By shorting, say, a A2 pad, you"re making A2 bit in the address a 0 and therefore are changing the I2C address. (shorting these pads is as simple as making a solder bridge.) That might come in very handy if you want to add one screen and 8 buttons, or two screens, or... Arbitrary combination of screen and buttons - my scripts are able to use different addresses, as you can see, and they do not generally interfere between themselves, so using both a screen and buttons works great =) But about addresses...
Also, in case of multiple backpacks there"s one more problem. All of those boards have onboard I2C pullups. That"s good for a single MCU-backpack combo but as the adapter size starts to increase, the common value of all those pullups starts to decrease (Electronics 101 - putting resistors in parallel), and as it decreases, it becomes more and more hard for backpacks&MCU to drive the line low, which can affect the communication negatively. To aviod that, you might need to remove some of the pullups, you can even leave just a single pair of them, and, as the Raspberry Pi boards all have pullups, you can basically remove all the SDA&SCL pullups from the boards. It"s easy to find them on the boards - these are the resistors whose one side is attached to VCC and other is attached either to SDA or to SCL.
If you have 2 different I2C buses, though, you can simply use one bus per one adapter, or even up to 16 adapters (including the revision trick) on one bus, making the numbers enormously big, if you need that many =) Just remember to specify different bus numbers, mmkay?
LCD character displays are a simple and a cost-effective way to display a text. Thanks to the HD44780 controller, the control of the modules has become very simple. However, one must occupy many GPIOs for it. An alternative is the I2C data bus, which means that only two GPIOs are used.
In this tutorial a 20×04 HD44780 character display is controlled using a I2C display adapter. A logic converter is used to adjusting the voltage level for the module without damaging GPIOs.
The Raspberry Pi GPIOs can not get more than 3.3V voltage, but there are some modules (like this display), which send and want to receive 5V signals. For this, a Logic Level Converter can be used, which has 2 sides. On one side those connections that are running on 3.3V are connected and on the other those with 5V. You can recognize this at different characteristics (LV – HV), as you see in the following picture:
If you have already connected the display, you can now test whether it has been detected (if you have one of the first Raspberry Pi’s [Rev.1], you have to pass 0 instead of 1):
The first parameter of the lcd_display_string is for the text and the second for the row. You do not have to change all lines at once, but you can not easily replace individual characters. For this, the entire text (with the character changed at the desired position) would have to be retransmitted.
The contrast of my I2C adapter was at the beginning very low. If nothing should be shown, test the wheel on the back and look obliquely on the display.
Raspberry Pi 16×2 LCD I2C Interfacing and Python Programming– I have been using 16×2 LCD for quite a long time in different Arduino and IoT related projects. You know we have two types of the 16×2 LCD, the normal one used more wires and the other one is based on the I2C interface which needs only two wires.
If you have the plain version of this display then this tutorial is not for you. The plain version is not practical anyway it would use a lot of GPIO Pins and it has a complicated programming requirement.
With this version you need only four pins and the programming model is very simple. Other than the display you will need some wires. This is what I will be using.
The right-hand side matches the backpack pins, while the left hand-side will go to a breadboard. You also need a small Phillips screwdriver to adjust the contrast.
The backpack module uses the I-squred-C (or I2C) protocol to communicate with the Raspberry Pi, which uses only two wires: SDA and SCL (data and clock). Please note that the display is a 5 volt device, and it is powered by 5 volts, but due to design of the I2C protocol, and the fact that the Raspberry Pi is the controlling device, it is safe to connect such display to the Raspberry Pi directly.
I suggest using wires of different colors to connect the LCD display. This minimizes the risk of damage due to incorrect connections. For example, I’m using
I use the cobbler connector with a breadboard, but the display can be connected to the GPIO headers directly, you’ll just need to use different wires. 5 volts and ground connections are close to each other here, while the SDA and SCL line are connected on the opposite side.
Before you start using the I2C 16×2 LCD display with Python, you need to make sure that the I2C protocol is enabled on your Raspberry Pi. You can use the sudo raspi-config utility to take care of that. This program is navigated using keyboard arrows, tab and the Enter key. Look for I2C in the interfacing options and enable it. Enabling I2C requires a reboot.
Once the system is back you can check whether the I2C bus is active, I2C protocol supports multiple devices connected to the same bus, and it identifies each device by their hardware address. The i2cdetect command can be used to see what is connected and what the addresses are.
And you can also adjust the contrast using a small Phillips screwdriver. Set it somewhere in the middle. Be careful not to short anything with the screwdriver while you make the adjustment. Looks like my display is ready to go.
The 27 hexadecimal addresses happen to be the most common, but your display’s address may be different. For example, it could be 3f. This will depend on the chip version of the backpack module. As long as the i2cdetect command shows the display is connected, you are good to go.
The easiest way to program this 16×2 I2C LCD display in Python is by using a dedicated library. There are many to choose from. I like things simple, so the library I recommend is rpi_lcd.
This library has the default 27 address hard-coded. If your display has a different address you will need to change it. You need to find the library on your system and the following command should do that for you.
I use the clear function at the end of the program, otherwise the message will stay on the display after the program ends. The two numbers (1 and 2) at the end of the text function indicate which line of the display to use.
This is an opportunity to adjust the contrast, especially if the display does not show anything, if you don’t see the “Hello, Raspberry Pi!” message. The adjustment only affects the letters, not the backlight. The backlight in this model is not adjustable, it’s always on, but you can turn it off by removing the jumper on the backpack.
A window will pop up with different tabs to adjust settings. What we are interested is the Interfaces tab. Click on the tab and select Enable for SPI. At this point, you can enable additional interfaces depending on your project needs. Click on the OK button to save.
We recommend restarting your Pi to ensure that the changes to take effect. Click on the Pi Start Menu > Preferences > Shutdown. Since we just need to restart, click on the Restart button.
These represent SPI devices on chip enable pins 0 and 1, respectively. These pins are hardwired within the Pi. Ordinarily, this means the interface supports at most two peripherals, but there are cases where multiple devices can be daisy-chained, sharing a single chip enable signal.
The Serial 7-Segment display is particularly useful for testing serial interfaces, because it can accept command from a UART, SPI, or I2C. Make sure to solder header pins on the 7-segment display before wiring.
Which generates an executable spitest. When we run ./spitest, it will exercise each of the segments of the display. It illuminates a segment in each digit for 5 seconds, before moving to the next segment. It takes about 40 seconds overall.
I am thinking of buying a Pico for a project I"m working on, but I can"t figure out how to use an i2c lcd screen with it. In the product page for the Pico there is a picture of the Pico with a screen attached to it:
My question is what is the simplest way to program a 16 by 2 lcd screen like the one in the picture with micropython and how would I go about doing so. Thanks in advance for any advice.
There a C examples for exactly that display in the pico-examples tree, Micropython should also be pretty easy. The main issue is ensuring you have a 3.3v device rather than 5v. Or use level shifters to compensate.
The modules I use have a jumper for the 5v feed to the backlight. Pull the jumper and feed the display with 5v from the PI. The electronics can get 3v3 and the I2C feeds from the PI and the unit will work perfectly.
I found a datasheet for a 2004A LCD display that indicated the character code of 253 for ° but haven"t been able to work out how to send that (LCD.display(253, c=16, l=1) just displays "253")
Currently, I don"t know how to do this. I could sure look into it. So it"s a (Degrees) symbol you are trying to display? Normally I would just use an asterix for that.
In the lcd.api.py, it specifies 2 methods of putting charecters, lcd.putstr() or lcd.putchar() or lcd.custom_char(). I don"t know how they work for now but you could look at that file and the comments attached to the commands.
I found a datasheet for a 2004A LCD display that indicated the character code of 253 for ° but haven"t been able to work out how to send that (LCD.display(253, c=16, l=1) just displays "253")
From the i2c.scan used the address into the code i2c.writeto(39, "hello"). But nothing happens. If I connect another i2C LCD and run i2C scan, I get the exact same address 39. If I connect two i2c LED, I only get the one 39 address reported.
Hey Andrew, those codes are actually designed for the Seed Studio grove RGB LCD. They require a sequence of hex codes to initialize the display and have a different I2C controller. If you can tell me or attach a picture of the LCD I can help you with what code you would require. As I commented previously, most of the Amazon I2C LCD backpacks use a PCF8574 and they can be controlled by the code I had directed people to with the GitHub link.
To answer the question you also originally asked, the address is in decimal and you would have to change it for one of the displays to differentiate which one you are communicating with.
A BIG THANK YOU Tyler, between you and dhylands, I have managed to get the pico to power the LCD. Where I was going wrong was I assumed that all things were equal, that one i2c LCD would be the same as any other. No mention was made in "Getting Started with MicroPython on Raspberry Pi Pico" in the chapter on i2c that you had to buy a specific i2c LCD (which is expensive and difficult to get hold of).
The code they publish just will not work with any other LCD. So what I have leant is this., Most i2c LCD"s work in 5 v, that is to say the data coming into the LCD has to be at 5 v. The pico data is at 3v, so you need an additional bit of hardware, 3.3 to 5v level translator. You also need some additional code. https://github.com/t-622/rpi-pico-i2c-lcd.
I had the same problem. Sadly the serial LCD used in the book is not your usual Hitachi character LCD with an I2C backpack on it. It is a Sparkfun product which has an AVR microcontroller to handle the I2C interface and additionally handles the complexity of programming the Hitachi display, I discovered this the hard way after some happy hours of sending instructions to the LCD and getting unusual results. I’ve used the cheap I2C backpacks in quite a few projects on different hardware over the years but this is the first time I’ve had problems. Given that I’m a beginner at Python ( though not programming) I initially thought it was me,
It’s also worth noting that the serLCD is quite hard to find in the U.K. Mouser U.K. have it but it is £22.82 about 4 times the price of a standard LCD and backpack from Amazon.
I’m going to give the library mentioned above a try with my collection of elderly Hitachi LCDs. If anyone wants to understand how they work I commend “How to use intelligent LCDs “ by Julyan Ilett which was published in “Everyday Practical Electronics “ in 1997. It’s in two parts and the pdf is free from a number of sites.
Once I’d found a missing “import machine “ statement in the test script T622’s library works very well. Many thanks. I’m using a cheap I2C backpack. I’m powering the LCD from a separate 5 volt supply and connecting the data lines directly to the Pico without a voltage converter, but with a common Earth. I’m pretty sure the I2C hardware specifications permit 3v3 for the data lines. Either way mine works.
i bought an lcd2004a from amazon, tried the code in the "getting started with micropython on raspberry pi pico" book. had no luck so went looking for drivers, found one that didn"t work with the pico, I messed about with it a little and managed to get it to work
Once I’d found a missing “import machine “ statement in the test script T622’s library works very well. Many thanks. I’m using a cheap I2C backpack. I’m powering the LCD from a separate 5 volt supply and connecting the data lines directly to the Pico without a voltage converter, but with a common Earth. I’m pretty sure the I2C hardware specifications permit 3v3 for the data lines. Either way mine works.
Connecting an LCD to your Raspberry Pi will spice up almost any project, but what if your pins are tied up with connections to other modules? No problem, just connect your LCD with I2C, it only uses two pins (well, four if you count the ground and power).
In this tutorial, I’ll show you everything you need to set up an LCD using I2C, but if you want to learn more about I2C and the details of how it works, check out our article Basics of the I2C Communication Protocol.
There are a couple ways to use I2C to connect an LCD to the Raspberry Pi. The simplest is to get an LCD with an I2C backpack. But the hardcore DIY way is to use a standard HD44780 LCD and connect it to the Pi via a chip called the PCF8574.
The PCF8574 converts the I2C signal sent from the Pi into a parallel signal that can be used by the LCD. Most I2C LCDs use the PCF8574 anyway. I’ll explain how to connect it both ways in a minute.
I’ll also show you how to program the LCD using Python, and provide examples for how to print and position the text, clear the screen, scroll text, print data from a sensor, print the date and time, and print the IP address of your Pi.
I2C (inter-integrated circuit) is also known as the two-wire interface since it only uses two wires to send and receive data. Actually it takes four if you count the Vcc and ground wires, but the power could always come from another source.
Connecting an LCD with an I2C backpack is pretty self-explanatory. Connect the SDA pin on the Pi to the SDA pin on the LCD, and the SCL pin on the Pi to the SCL pin on the LCD. The ground and Vcc pins will also need to be connected. Most LCDs can operate with 3.3V, but they’re meant to be run on 5V, so connect it to the 5V pin of the Pi if possible.
If you have an LCD without I2C and have a PCF8574 chip lying around, you can use it to connect your LCD with a little extra wiring. The PCF8574 is an 8 bit I/O expander which converts a parallel signal into I2C and vice-versa. The Raspberry Pi sends data to the PCF8574 via I2C. The PCF8574 then converts the I2C signal into a 4 bit parallel signal, which is relayed to the LCD.
Before we get into the programming, we need to make sure the I2C module is enabled on the Pi and install a couple tools that will make it easier to use I2C.
Now we need to install a program called I2C-tools, which will tell us the I2C address of the LCD when it’s connected to the Pi. So at the command prompt, enter sudo apt-get install i2c-tools.
Next we need to install SMBUS, which gives the Python library we’re going to use access to the I2C bus on the Pi. At the command prompt, enter sudo apt-get install python-smbus.
Now reboot the Pi and log in again. With your LCD connected, enter i2cdetect -y 1 at the command prompt. This will show you a table of addresses for each I2C device connected to your Pi:
We’ll be using Python to program the LCD, so if this is your first time writing/running a Python program, you may want to check out How to Write and Run a Python Program on the Raspberry Pi before proceeding.
I found a Python I2C library that has a good set of functions and works pretty well. This library was originally posted here, then expanded and improved by GitHub user DenisFromHR.
There are a couple things you may need to change in the code above, depending on your set up. On line 19 there is a function that defines the port for the I2C bus (I2CBUS = 0). Older Raspberry Pi’s used port 0, but newer models use port 1. So depending on which RPi model you have, you might need to change this from 0 to 1.
The function mylcd.lcd_display_string() prints text to the screen and also lets you chose where to position it. The function is used as mylcd.lcd_display_string("TEXT TO PRINT", ROW, COLUMN). For example, the following code prints “Hello World!” to row 2, column 3:
On a 16×2 LCD, the rows are numbered 1 – 2, while the columns are numbered 0 – 15. So to print “Hello World!” at the first column of the top row, you would use mylcd.lcd_display_string("Hello World!", 1, 0).
You can create any pattern you want and print it to the display as a custom character. Each character is an array of 5 x 8 pixels. Up to 8 custom characters can be defined and stored in the LCD’s memory. This custom character generator will help you create the bit array needed to define the characters in the LCD memory.
The code below will display data from a DHT11 temperature and humidity sensor. Follow this tutorial for instructions on how to set up the DHT11 on the Raspberry Pi. The DHT11 signal pin is connected to BCM pin 4 (physical pin 7 of the RPi).
By inserting the variable from your sensor into the mylcd.lcd_display_string() function (line 22 in the code above) you can print the sensor data just like any other text string.
These programs are just basic examples of ways you can control text on your LCD. Try changing things around and combining the code to get some interesting effects. For example, you can make some fun animations by scrolling with custom characters. Don’t have enough screen space to output all of your sensor data? Just print and clear each reading for a couple seconds in a loop.
Add any 16x2 or 20x4 LCD-screen with a Hitachi HD44780 controller using either a port expander connected through I2c or just wire through GPIO 4 or 8 bit.
1 LCD-screen Hitachi HD44780 controller (PCF8574, or MCP23008 or MCP23017) with an I2c port expander. Or just wire through GPIO 4 or 8 bit. We recommend using a LCD-screen with an I2c port expander as it uses less wire (only 4) and is faster and more stable.
If your LCD has a PCF8574T chip from Texas Instruments, its default I2C address is 0x27Hex. If your LCD has a PCF8574AT chip from NXP semiconductors, its default I2C address is 0x3FHex. So your LCD probably has an I2C address 0x27Hex or 0x3FHex.
Since the Raspberry Pi GPIO only handle 3.3v, it will therefore be a good idea to use a I2C-safe Bi-directional Logic Level Converter so you don’t fryed your pi.
R2: Potentiometers: 10K Ohms. Controls the contrast and brightness of the LCD. Using a simple voltage divider with a potentiometer, we can make fine adjustments to the contrast.